How to add event listener to each class in an html collection?

前端 未结 2 415
时光说笑
时光说笑 2021-01-17 07:24

I\'m attempting to get all elements by the class of \'element\' and adding an event listener to each of them. however, getElementsByClassName() returns and html

2条回答
  •  心在旅途
    2021-01-17 07:42

    Sorry! My code above works fine! Turns out that my JS code was executing before the DOM was done loading. Thanks for the the help. The solution was to add an evt listener document object and then call the function once it was completely loaded:

    document.addEventListener("DOMContentLoaded", function(){
                      var tableElements = document.getElementsByClassName("element");  
                 for(var i=0;i

提交回复
热议问题