Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript equivalent for jQuery .on() with additional selector [duplicate]

Here is JSFiddle exapmle: https://jsfiddle.net/1a6j4es1/1/

$('table').on('click', 'td', function() {
    $(this).css('background', 'green');
});

How can this code be rewritten in plain JavaScript?
Callback function should work even for new td elements inside the table element.

Update: I found out a very short and clean solution: https://jsfiddle.net/1a6j4es1/28/

function delegateSelector(selector, event, childSelector, handler) {

    var is = function(el, selector) {
      return (el.matches || el.matchesSelector || el.msMatchesSelector || el.mozMatchesSelector || el.webkitMatchesSelector || el.oMatchesSelector).call(el, selector);
    };

    var elements = document.querySelectorAll(selector);
    [].forEach.call(elements, function(el, i){
        el.addEventListener(event, function(e) {
            if (is(e.target, childSelector)) {
                handler(e);                
            }
        });
    });
}

delegateSelector('table', "click", 'td', function(e) {
    e.target.style.backgroundColor = 'green';
});
like image 461
Dmitry Avatar asked Aug 16 '26 23:08

Dmitry


1 Answers

Add an ID to the element you wish to click on, and use this code:

document.getElementById("tableId").addEventListener("click", function(e){
e.target.style.background = 'green';
});
like image 188
Eyal Avatar answered Aug 18 '26 18:08

Eyal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!