How do you get elements from a javascript HTMLCollection

后端 未结 3 1125
迷失自我
迷失自我 2021-02-07 04:30

I can\'t understand why I cant get elements from a HtmlCollection. This code example:

 var col = (document.getElementsByClassName(\"jcrop-holder\"));
 console.lo         


        
3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-07 05:27

    Taken from : Can't access the value of HTMLCollection

    The problem is you have placed the script in the header which gets executed before the html elements are loaded, so getElementsByClassName() will not return any elements.

    One solution is to wait for the html elements to be loaded then execute your script, for that you can use the window objects load event

    window.addEventListener('load', function () {
    var eles = document.getElementsByClassName('review');
    console.log(eles);
    console.log(eles.length);
    console.log(eles[0]);
    })
    

    Or you can place your script at the bottom of the body element instead of in head so that by the time the script is parsed and executed the elements are loaded in the dom

提交回复
热议问题