Skip to content Skip to sidebar Skip to footer

Addeventlistener Dynamically To Newly Added Classes

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 have

Solution 1:

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 foundif (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')){
}

Post a Comment for "Addeventlistener Dynamically To Newly Added Classes"