Okay, I have a todo app that i\'m creating with JS. I have an addtodo function which adds the items when clicked and also runs a for loop for each of these list elements, which
Event Delegation is the way forward. Its philosophy is very simple, event listener is attached to static-parent-element then it analyses the bubbled event.target
. if match is found then the desired operation can be performed.
document.querySelector('.static-parent-element').addEventListener("click", function(e) {
if(e.target && e.target.classList.contains('thevalue')) {
// thevalue item found
if (this.parentElement.classList.contains('normal')) {
this.parentElement.classList.toggle('high');
}
}
});
Element.matches() API can also used to validate element matches a given selector.
The
Element.matches()
method returns true if the element would be selected by the specified selector string; otherwise, returns false.
if(e.target.matches('.thevalue')){
}