1

I'm trying to add event listener to multiples element I created before in my script.

I've tried that method first :

document.body.addEventListener('click', function (event) {
    if (event.target.class === "deleteCommentButton"){
        deleteComment();
    }
})

But it doesn't seems to work, so I'm now trying to do with this method, which seems to be better :

const addEventTobutton = () => {
    document.querySelectorAll('.deleteCommentButton').addEventListener('click', deleteComment);
    document.querySelectorAll('.modifyCommentButton').addEventListener('click', modifyComment);
}

does someone have an explanation for me to understand why my code isn't working ?

thanks

0

3 Answers 3

2

in your first code you are adding an event listener to the document body, rather than your element. it is not the ideal way to create an event listener, as it is quite inefficient. instead add the listener to the element you want to detect the event on.

const newElement = document.createElement( 'div' );
newElement.addEventListener( 'click', () => {} );

on top of that, to detect an element's class, you should use classList.contains()

if ( newElement.classList.contains( 'deleteCommentButton' ) ) {
Sign up to request clarification or add additional context in comments.

Comments

1

QuerySelectorAll is an array and therefore, I couldn't add event on it. Need to loop with something like :

  arrayDeleteButton.forEach(deleteBtn => {
        deleteBtn.addEventListener('click', deleteComment)
    });
    arrayModifyButton.forEach(modifyBtn => {
        modifyBtn.addEventListener('click', modifyComment);
    }) 

is this a better solutions than what you guys proposed or should I go your way ?

Comments

0

The answer is easy you should use classList instead of class for the first approach to work .

That will give all the classes of an element.

For that you can use:

 event.target.classList.contains("deleteCommentButton")

1 Comment

this method of testing for a class will also return true if the element had a class called deleteCommentButtonContainer along with other ways of returning a false positive. you may want to use classList.contains()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.