How to add an event to all elements with the same class?

Asked

Viewed 504 times

3

How do I add an event to all elements in the same class?

The code I wrote doesn’t work:

var tabela = document.querySelectorAll('.status');
for (var i = 0; i <= tabela.length; i++) {
    tabela.addEventListener('dblclick', function(event) {
        event.target.parentNode.remove();
    });
}

And I get the following mistake:

Uncaught Typeerror: table.addeventlistener is not a Function at (file.js).

  • 3

    have to do tabela[i].addEvent... and is going one more position... would be < tabela.length

  • Oops, thank you! Helped me a lot! :)

1 answer

4

The method querySelectorAll returns an object NodeList, who does not have the method addEventListener on your prototype. It means that you cannot add a Listener event to all elements of a NodeList simultaneously. For this, you must iterate to each of them by adding the Listener to each element.

You iterated correctly in your code, using the repeat loop for. The problem that generates the error in question occurs in the following line:

tabela.addEventListener('dblclick', function(event) { /* ... */

Because tabela refers to the value returned by querySelectorAll.

Then, as cited by one of the comments of the question, you need to change to:

// Acessar o elemento da iteração atual.
//    ↓↓↓
tabela[i].addEventListener('dblclick', function(event) { /* ... */

This way, you will be able to add the Listener to each element of the NodeList individually.


You can even use the forEach, present in the prototype of NodeList, to do this in a simpler way:

document.querySelectorAll('.status').forEach((el) =>
  el.addEventListener('dbclick', (event) => {
    event.target.parentNode.remove();
  })
);

So you avoid possible errors in the loop for, such as using the operator less than or equal to (<=), when it should use the operator less than (<).

See why the "error" in using this operator:

const els = [1, 2, 3];

for (let i = 0; i <= els.length; i++) {
  console.log(els[i]);
}

Will be printed a undefined in the end, since els[3] (being 3 equal at the length of array els) does not exist. so when using the less than (<), you avoid this problem.

  • Oops, thank you! It helped me a lot, now I understand better where the mistake was and why :)

  • @Filipefrs, if that answer answered your question, don’t forget to mark it by clicking on the icon of check in below the place of votes. :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.