Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

addEventListener is not a function error [duplicate]

Tags:

javascript

I am trying to convert the text in a td cell to "Clicked!" when it is clicked upon, but it throws up an error when loading the JS. I have read around and know that it can't use an array like this but I don't know how to fix it.

window.addEventListener("load", table)

function table(){
    var tables = document.getElementsByTagName("td");
    tables.addEventListener("click", clicked);
}
like image 996
Goo Avatar asked Mar 12 '23 04:03

Goo


1 Answers

document.getElementsByTagName returns not a Node object, but NodeList object. You can access Node objects by index.

Sample:

var tables = document.getElementsByTagName("td");

if (tables.length) {
 tables[0].addEventListener("click", clicked);
}

https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByTagName

like image 113
gevorg Avatar answered Mar 21 '23 11:03

gevorg