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.
have to do
tabela[i].addEvent...
and is going one more position... would be< tabela.length
– vik
Oops, thank you! Helped me a lot! :)
– FilipeFrs