Can someone please help with converting this code to plain JS:
$(document).ready(function() {
$("textarea").bind("keydown", functi开发者_开发问答on(event) {
var textarea = $(this).get(0);
//further will need only textarea and event vars
}
});
I don't care about cross browser compatibility as long as it works in current FF and Chrome.
Your selector is quite simple, you are looking for all the textarea
elements, then you can use the document.getElementsByTagName
method.
To simulate $(document).ready
, we can bind the DOMContentLoaded
event e.g.:
document.addEventListener('DOMContentLoaded', function () {
var allTextAreas = document.getElementsByTagName('textarea');
// event handler
var handler = function (event) {
var textarea = this;
//...
};
// iterate over the textareas and bind the event
for(var i = 0, len = allTextAreas.length; i < len; i++) {
allTextAreas[i].addEventListener('keydown', handler, false);
}
}, false);
For CSS selectors, you can use the querySelectorAll
method, available on both browsers you are targeting.
See also:
- Selectors API
- Thoughts on querySelectorAll
Why convert it to "plain JS"? jQuery essentially is plain JS. It's just a language built around Javascript. What is it that's not working for you with jQuery
精彩评论