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
1 Answer
Reset to default 6Yes. 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
版权声明:本文标题:javascript - Is there any way to add an Event Listener to a class? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742370907a2462214.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论