javascript

add an event listener on an element I've created in javascript


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


Solution

  • 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")