How do you get elements from javascript HTMLCollection

I can not understand why I can not get the elements from the HtmlCollection. This code example:

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

outputs this output to the console:

enter image description here

I am trying to get the dic.jcrop-holder object, but I cannot get it from the col variable. None of this works:

  console.log(col[0]); // undefined console.log(col.item(0)); // null // check length of collection console.log(col.length); // 0 

So, if the length is 0, why does the console display a length of 1, as well as objects inside? When I open node, it contains children. What's happening?

Here are a few advanced sites. I did not expand div.jcrop.holder because it is too long. Here are the baby items:

enter image description here

+5
source share
2 answers

Taken from: Unable to access HTMLCollection value

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

One solution is to wait for the html elements to load and then execute your script, for which you can use the window object 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 put your script at the bottom of the body element instead of the head, so that by the time the script is analyzed and launched, the elements are loaded in dom

+2
source

I ran into the same problem, and the solution to this problem was to put my script at the end of the document in order to wait for the entire document to load before changing or selecting HTMLCollection elements. Hope this helps.

0
source

Source: https://habr.com/ru/post/1232785/


All Articles