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

Bizu
  • 17
  • 6
  • Related question: [What is DOM Event delegation?](https://stackoverflow.com/a/1688293/943435) – Yogi Sep 25 '22 at 20:06

3 Answers3

1

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' ) ) {
dqhendricks
  • 19,030
  • 11
  • 50
  • 83
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 ?

Bizu
  • 17
  • 6
  • 1
    This is a good answer, though querySelectorAll actually returns a [nodeList](https://developer.mozilla.org/en-US/docs/Web/API/NodeList) which is not quite the same as an array. – Yogi Sep 25 '22 at 20:13
0

The answer is easy you should use className 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.className.contains("deleteCommentButton")
  • 1
    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()` – dqhendricks Sep 25 '22 at 20:04
  • 1
    This might be the accepted answer, but it's not the best answer as @dqhendricks has explained. Using string methods to determine classes and attributes can lead to difficult to resolve bugs. – Yogi Sep 25 '22 at 20:20