开发者

How to convert selectors and event capturing from jQuery to plain JS?

开发者 https://www.devze.com 2023-01-09 12:55 出处:网络
Can someone please help with converting this code to plain JS: $(document).ready(function() { $(\"textarea\").bind(\"keydown\", functi开发者_开发问答on(event) {

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

0

精彩评论

暂无评论...
验证码 换一张
取 消