The output of console.log in a browser context versus a code environment can vary

As I was building a carousel, I became completely lost with my HTML structure:

<!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>

Then, looking at my JavaScript code:

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

Despite having 4 items with the class ".carousel_item", the console is inexplicably showing 0 instead of 4. When I tried the same code in the browser console, it displayed the correct number. I'm unsure if the issue lies with my code or if the browser is malfunctioning. Any assistance would be greatly appreciated!

Answer №1

When it comes to parsing HTML documents, the process is done from top to bottom. In the event that a `script` tag is encountered, all other parsing activity comes to a halt until the script completes its execution.

Consequently, any elements positioned after the `script` tag will not appear in the DOM accessible to the script.

To address this issue, it is advisable to relocate the `script` tag towards the end of the `body` tag as shown below:

<!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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Arranging array based on the sequence of another array

There are two arrays that I am working with: Main array: const items = [ "Лопата 123", "Empty Forest", "Forever young", "My ears", "Most Important", "16 Tons", "Operation ...

Changing data automatically in PHP through radio buttons

As a beginner in PHP, I am working with 2 radio buttons where one is checked by default. When the page loads, I want to display content based on the default selected radio button. ...

Add a new value to the translation token using ng-bind

I'm attempting to loop through an element 5 times using ng-repeat and track by $index. Following that, I aim to utilize the value from $index to supplement a translation token. This appended index value corresponds with the token which retrieves the a ...

Does Google Chrome have a strange way of interpreting CSS?

Almost done with my website and it looks great on Firefox and IE 8, but Chrome is causing issues. Here's how it appears on FF: And here's Chrome: Notice how Chrome resizes the first image even though the code is the same as the one below? Che ...

In Angular 5, a variable's value becomes undefined once it is subscribed to outside of its assigned

I keep encountering an undefined value when trying to assign the subscribed value to a variable in my code snippet below. service.ts getIpAddress() : Observable<any> { return this.http .get(this.Geo_Api) .map((response: ...

Implementing a blur effect on a CSS loader

I have successfully implemented a loader feature where a loading animation is displayed upon clicking the submit button, indicating that the form submission is in progress. However, I am encountering an issue when trying to apply a blur effect to the entir ...

What could be causing the post method to fail in this AngularJS example?

After successfully reading a JSON file in my sample code, I encountered an issue when trying to update the JSON file. The error message "Failed to load resource: the server responded with a status of 405 (Method Not Allowed)" appeared, even though the data ...

Head over to the registration page if your login attempt is unsuccessful

I am currently working on developing a basic login page. The process involves users signing up on the register page first, and then attempting to log in. If the login credentials match with the database, they are directed to the homepage. However, if the u ...

Distinguishing between Javascript Array Objects and Array-Like Objects: An Elucidation

While attempting to convert an array-like object into a string using JSON.stringify, I discovered that the function was not working correctly when the array-like object was declared as an array object. For more clarity, please refer to the following --> ...

Is there a way to personalize the chart tooltip in jqplot to fit my preferences?

I have a chart that displays data. I would like the x-axis labels to show in the format MM/DD, and in the tooltip, I want to display data in the format HH:y-axis. For example, in the chart below, I want the x-axis labels to be 'Oct 15','Oct ...

Next.js API route is showing an error stating that the body exceeds the 1mb limit

I'm having trouble using FormData on Next.js to upload an image to the server as I keep getting this error. I've tried various solutions but haven't been able to resolve it yet. This is my code: const changeValue = (e) => { if (e.target ...

Issue with toggleClass functionality (potential coding glitch)

I am attempting to display my div once the button is clicked. Below is the code snippet: <div class="post-menu"> <button class="button"> <i class="uil uil-ellipsis-h"></i> </button> ...

React application created with create-react-app that uses multiple environment files for varying configurations

I've been working on setting up various environment files for a React project (using create-react-app). I referred to the official documentation, but I encountered the following error: '.env.development' is not recognized as an internal or ...

Upon returning to the previous page, the checkbox remains checked and cannot be unchecked

Here is the code I'm using to append checkbox values with a hash in the URL. However, when navigating back, the checkboxes remain checked. Take a look at the code snippet below: <html> <head> <script src="http://ajax.googleapis.com/aja ...

Verify whether the combobox has been chosen

Currently, I am dealing with two comboboxes and need to determine which one is selected. My intention is to achieve this using ajax and jquery within a JSP file. if(combobox1 is selected) { perform action 1 } if(combobox2 is selected) { perform actio ...

Generating a JavaScript array using concealed data

var a1=$("#orderprogress").val().toFixed(2);//a1=50 var a2=$("#poprogress").val().toFixed(2); //a2=70 If I were to create an array in this format, how should I proceed? graphData = new Array( [a1 value,'#222222'],//[50,'#22222 ...

Unlock the message with Proxy Re-encryption technology

I'm completely new to encryption and am experimenting with a Node JS library called recrypt-js for Proxy Re-encryption using CryptoJS. I tried encrypting the message "test data" following the example provided, but I'm facing difficulty when tryin ...

Issue with highlighting when one string overlaps with another

I am facing a challenge with handling a string that contains Lorem Ipsum text. I have JSON data that specifies the start and end offsets of certain sections within the text that I need to highlight. The approach I am currently using involves sorting the JS ...

Transitioning the font stack from SCSS to JSS (cssinjs)

We are currently implementing a variety of custom fonts with different weights for various purposes. With our entire stack now using Material UI with JSS theming and styling, we aim to eliminate the remaining .scss files in our folder structure. All the f ...

How can I display pure HTML in a Pyramid view?

I am completely new to Pyramid (and relatively inexperienced with web frameworks in general). My goal is to reach a point where I can retrieve raw HTML from a view in order to format data fetched from my mongoDB database. The __init__.py in my Pyramid pr ...