Search code examples
javascripthtmlcssgetelementsbytagnamegetelementsbyclassname

document.getElementsByClassName creates null array when the class exists in HTML


I am following W3Schools' tutorial on creating a Slideshow in HTML/CSS/Javascript, located here. In the HTML code, I have created several elements that are within the mySlides class; however, when I call document.getElementsByClassName("mySlides") I get a null array.

Here is some of the HTML code of elements within the mySlides class:

<div class="mySlides fade">
    <div id="intro">
        <p>Click to Start!</p>
        <button type="button" id="startButton" onclick="start()">Start!</button>
    </div>
</div>

Here is the Javascript code where I call upon accessing the mySlides elements:

var slides = document.getElementsByClassName("mySlides");
console.log(slides.length); // prints "0"
console.log(slides[0]); // prints "undefined"

Any ideas on why document.getElementsByClassName("mySlides") isn't able to access the mySlides elements? Thank you for your help.


Solution

  • The HTML document might not be ready by the time your script is executed. If so, you have to execute code after DOMContentLoaded.

    The DOMContentLoaded event is fired when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.

    document.addEventListener("DOMContentLoaded", function(event) {
      var slides = document.getElementsByClassName("mySlides");
      console.log(slides.length);
      console.log(slides[0]);
    });
    <div class="mySlides fade">
        <div id="intro">
            <p>Click to Start!</p>
            <button type="button" id="startButton" onclick="start()">Start!</button>
        </div>
    </div>