How do you get elements from a javascript HTMLCollection

后端 未结 3 1123
迷失自我
迷失自我 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:01

    I was facing the same issue and the solution to this problem was to place my script in the end of the document, in order to wait to the whole document to be loaded before start changing or selecting the HTMLCollection elements. Hope it helps.

    0 讨论(0)
  • 2021-02-07 05:04

    look this code, with it you can use a class attribute for a HTMLColletion

      var eles = document.getElementsByClassName('className');
        for (let i = 0; i < eles.length; i++) {            
                eles[i].addEventListener('click',function(){
                    // code ex. eles[i].querySelector(".contenedor").classList.toggle('ocultar');
                    // code here...
                })
    
        } 
    
    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题