1

I have a problem with parent.getElementsByClassName() in javascript. I am working on a slider and wanted to count how many slides are put into it, but I've encountered a massive problem.

From my understanding, this command should make an array of all objects with a selected class name, but it's not working properly in my case. Whenever I put this code into my .js file it doesn't want to coop.

let slides = document.getElementsByClassName("slide") ;
console.log(slides); // returns HTMLCollection[]
// 0:div#id1hehe.slide
// 1: div.slide

and when I do

console.log(slides[0]);

it returns undefined.

When I put the same code into the browser console I get:

console.log(slides) // HTMLCollection(2) [div#id1hehe.slide, div.slide, id1hehe: div#id1hehe.slide]

and

console.log(slides[0]) // <div class="slide" id="id1hehe" style="margin-left: -89.0215%;">...

Can someone explain why is it like this?

  • The `HTMLCollection` you get from `getElementsByClassName` is a **live** collection. As of when you `console.log` it in your code, it's empty, but later DOM elements get created that have the matching class, so entries are added to it. When you expand it in the console later when those entries exist, you see them. See [the linked question's answers](http://stackoverflow.com/questions/38660832/) for more. – T.J. Crowder Aug 01 '20 at 12:43
  • I also recommend [the answers here](http://stackoverflow.com/questions/14028959/) -- it sounds like you have your `script` tag in the wrong place and aren't using `defer` or `type="module"` on it. If you don't use either of those attributes, put your `script` tag at the very end of the document, just prior to the closing `

    ` tag.

    – T.J. Crowder Aug 01 '20 at 12:44
  • 1
    Oh gosh... silly me. So I just need to get the script tag from head section to the end of body... Thanks. I'm so embarassed xD – Rafał Meler Aug 01 '20 at 12:45
  • There's no need! We've all done it. Happy coding! – T.J. Crowder Aug 01 '20 at 12:46

0 Answers0