0

I was creating a carousel. I don't know what the hell is going on anymore, in my HTML:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="Carousel.css">
    <script src="Carousel.js"></script>
    <title>Carousel</title>
</head>

<body>
    <h1>This is the Carousel</h1>

    <div id="carousel">
        <div class="carousel_item carousel_item--visible"><img src="Images/Sasuke.jpg" alt="" srcset=""></div>
        <div class="carousel_item"><img src="Images/Spider-man.jpg"></div>
        <div class="carousel_item"><img src="Images/The Dark Knight.jpg" ></div>
        <div class="carousel_item"><img src="Images/Arcane.jpg"></div>

        <div class="carousel_actions">
            <button id="carousel_button--prev"> < </button>
            <button id="carousel_button--next"> > </button>
        </div>
    </div>


</body>

</html>

and my JS:

let curr_pos = 0;
const slide = document.getElementsByClassName('carousel_item');
console.log(slide.length);

In this as you can see I have 4 items with .carousel_item so the console should display 4, however it is showing 0.But if I use console.log(slide.length) in Browser console then it shows 4.

Now either I have to start Js from scratch or the browser is gone mental. Please someone help!

Anuj Tanwar
  • 31
  • 1
  • 5

1 Answers1

2

HTML documents are parsed top to bottom. When a script tag is encountered, all other parsing stops until the script has finished execution.

Therefore, elements placed after the script tag will not be visible in the DOM to the script.

To solve this, move the script tag's position to the bottom of the body tag:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="Carousel.css">
    <title>Carousel</title>
</head>

<body>
    <h1>This is the Carousel</h1>

    <div id="carousel">
        <div class="carousel_item carousel_item--visible"><img src="Images/Sasuke.jpg" alt="" srcset=""></div>
        <div class="carousel_item"><img src="Images/Spider-man.jpg"></div>
        <div class="carousel_item"><img src="Images/The Dark Knight.jpg" ></div>
        <div class="carousel_item"><img src="Images/Arcane.jpg"></div>

        <div class="carousel_actions">
            <button id="carousel_button--prev"> < </button>
            <button id="carousel_button--next"> > </button>
        </div>
    </div>

    <script src="Carousel.js"></script>
</body>

</html>
Spectric
  • 30,714
  • 6
  • 20
  • 43