1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

jQuery(document).on("click","selector", function(e){});をpure javascriptで書き換える

Last updated at Posted at 2023-11-10

実際の要素ができる前でも処理が書けて便利だからと多用されていた

// jQuery
jQuery(document).on("click","selector", function(e){
    // 要素は$(this);
    var $el = $(this);
    // 処理
});

はpure javascriptだと

// javascript
document.addEventListener('click', function(e){
    let el;
    if(el = e.target.closest('selector')){
        // 要素は e.target.closest('selector')で取ると確実
        el;
        // 処理
    }
});

と書き換えられる。
面倒なのは2点、

  1. e.currentTargetは常にdocument
  2. selectorの子孫要素もMatchさせないといけないから要素を取るならclosestを使うと確実
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?