admin管理员组

文章数量:1336411

So I'm making a web hosted game, and I am trying to add an event to a class.

I couldn't really find some helpful info on the web, and I tried to use

document.getElementsByClassName("class").addEventListener("click", function(){…}); 

I want it to test if a certain item in a class is clicked but it keeps making an error like this - BattleMode.js:4 Uncaught TypeError: document.getElementsByClassName(...).addEventListener is not a function at BattleMode.js:4; if I try to do anything else it does not sense the div with the certain properties.

So I'm making a web hosted game, and I am trying to add an event to a class.

I couldn't really find some helpful info on the web, and I tried to use

document.getElementsByClassName("class").addEventListener("click", function(){…}); 

I want it to test if a certain item in a class is clicked but it keeps making an error like this - BattleMode.js:4 Uncaught TypeError: document.getElementsByClassName(...).addEventListener is not a function at BattleMode.js:4; if I try to do anything else it does not sense the div with the certain properties.

Share Improve this question edited Jun 26, 2019 at 0:59 JSSCRIPTER asked Jun 26, 2019 at 0:53 JSSCRIPTERJSSCRIPTER 351 silver badge5 bronze badges 1
  • "A class" is not something that exists in the way your code assumes. That method returns a list of elements, and you have to treat them individually. Alternatively, you can use event delegation via event handlers on the document object. – Pointy Commented Jun 26, 2019 at 0:54
Add a ment  | 

1 Answer 1

Reset to default 6

Yes. Just remember that getElementsByClassName() is plural - Elements:

var elements = document.getElementsByClassName("class");

for (var i=0; i<elements.length; i++) {
    elements[i].addEventListener("click", function(){…});
}

Note that getElementsByClassName() does not return an array. Instead it returns a NodeList which is an array-like object. So the usual array methods like .map(), .forEach() etc. are not available. NodeLists do have a .length property so you can iterate over them.

You can however convert them to arrays using Array.from or slice():

Array.from(document.getElementsByClassName("class"))
    .forEach(function(element){
        element.addEventListener("click", function(){…});
    });

本文标签: javascriptIs there any way to add an Event Listener to a classStack Overflow