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';
});
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';
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With