The document.getElementsByClassName method in JavaScript is returning an Array with a length property value of 0

My HTML contains a list of li elements with one class. I am attempting to collect them all and place them in an array to determine how many have been gathered. However, when I attempt to display the number using the .length property of the array returned by document.getElementsByClassName, it always shows as 0. Here is my code:

function activateFeedMain() {
        console.log('Function Called');
        var clickInfo = document.getElementsByClassName('miniInfo');
        var showInfo = document.getElementsByClassName('moreInfo');

        console.log(clickInfo.length);
}

activateFeedMain();

Here is the relevant HTML snippet:

<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<meta id="refresh" http-equiv="refresh" content="300">
<title>News and Events</title>
<link href="css/style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="scripts/hfreplacement.js"></script>
<script type="text/javascript" src="scripts/news.js"></script>
<style type="text/css">
    #content-col1 ul {list-style-type: none;}
    #content-col1 ul li {background-color: #66FFCC; border-radius: 5px; padding: 12px; margin-bottom: 8px;}
    #content-col1 ul li:hover {background-color: #FFFFCC;}
    .description {font-weight: bold; font-style: italic;}
    .date, .type, .approval {font-size: 12pt; padding-right: 25px; padding-left: 18px; display: inline-block; border-right: 1px solid black;}
    .date {padding-left: 0px;}
    .approval {border: none;}
    .invisible {display: none;}
    #content-col1 ul a:hover {text-decoration: none;}
    #content-col1 ul a {text-decoration: none; cursor: pointer;}

</style>
</head>

<body>
<div id="head"></div>

<div id="content">
    <div id="content-col1">
        <p class="note">Refresh for updates</p>
        <script>newsContent();</script>
    </div>

    <div id="content-col2">
        <h1>Latest</h1>
        <ul>
        </ul>
    </div>
</div>

<div id="foot"></div>
<script type="text/javascript">
    function activateFeedMain() {
        console.log('Function Called');
        var clickInfo = document.getElementsByClassName('miniInfo');
        var showInfo = document.getElementsByClassName('moreInfo');

        console.log(clickInfo.length);
    }

    activateFeedMain();
</script>
</body>
</html>

The script newsContent(); places all the lis into the ul. Interestingly, while console.log(clickInfo) successfully displays the array, there seems to be an issue with the .length property...

Moreover, upon using console.log(clickInfo[1]);, it returns undefined...

Answer №1

Interactive sample

The issue stems from the dynamic creation of content by your newsContent function happening asynchronously alongside the execution of your activateFeedMain function. As a result, when both functions are called simultaneously, the elements generated by newsContent may not be available at the time activateFeedMain runs.

To address this problem, you can modify the newsContent function to accept a callback that will execute upon completion of its tasks.

function activateFeedMain() {
    console.log('Function Called');
    var clickInfo = document.getElementsByClassName('miniInfo');
    var showInfo = document.getElementsByClassName('moreInfo');

    console.log(clickInfo.length);
}

// Wait for newsContent to finish before calling activateFeedMain()
newsContent(activateFeedMain);

In the implementation of newsContent, structure it to accommodate a callback like this:

function newsContent(callback){

    ...

    // Invoke callback upon completion
    if(typeof callback === 'function'){
        callback();
    }
}

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

Having trouble connecting DB and D3 using PHP. Struggling to follow D3noob's tutorial to completion

First and foremost, I want to express my gratitude to the amazing community here for all that I have learned. However, I'm currently facing some difficulties in finding the solution I need. I've encountered issues while trying to follow the inst ...

Utilizing PHP Variables in Ajax Calls: Transferring Data between JS and PHP

I've been struggling to grasp how to pass information from PHP to JavaScript and vice versa. I've spent an entire night trying to figure this out and would really appreciate it if someone could help me understand how to send two variables to an a ...

Is it possible to change button behavior based on input values when hovering?

Currently, I am attempting to create a webpage where users can input two colors and then when they press the button, a gradient of those two colors will appear on the button itself. <!doctype html> <html> <head> <script src=&apos ...

Choosing individual child elements, with matching names, from two distinct parent elements with identical names

As a beginner in coding, I understand that my code may be messy and redundant, so I apologize for any confusion it may cause. I am working on adding the final piece to my navigation bar. Below is the HTML code, and a fiddle link will be provided at the en ...

Can JavaScript trigger an alert based on a CSS value?

Hello, I am facing an issue. I have created a blue box using HTML/CSS and now I want to use JavaScript to display an alert with the name of the color when the box is clicked. Below is my code: var clr = document.getElementById("box").style.background ...

Ways to both retrieve a variable and clear it simultaneously

In my validator library, there are functions that sanitize and validate strings. These validator functions add error messages to an array called "errors" for each invalid input they encounter. After completing validation on all inputs, I collect the error ...

Glowing sphere in Three.js

Can someone help me with a coding dilemma I'm facing? I'm trying to create a sphere that functions as a source of light, like the sun. I've been experimenting with the meshPhongMaterial options emissive: color and shininess: intensity, but s ...

Obtain the complete list of all the dates and days within a specified month

Is there a way to retrieve all days and dates for a specific month instead of the current one? I have the code below which currently displays all the days in the current month, but I need to modify it to parse in a specified month. $list=array(); $month ...

Guide on managing firebase and webrtc tasks within a client-side component using Next.js 13

I developed a Next.js 13 application to share the camera feed using WebRTC and Firestore. Below is my page.tsx file where I am facing some challenges. I can't make this server-side because I'm using React hooks, and moving it to the client side i ...

Is there a way to adjust the width of a table cell in Material UI using React?

I encountered a problem where I am attempting to adjust the width of a table cell, specifically in Typescript. However, I am only able to choose between medium and small sizes for TableCellProps. Is there a workaround for this issue? I am looking to expand ...

How to choose multiple checkboxes in AngularJS by utilizing the shift key and mouse click feature?

Is it feasible to utilize shift and mouse click for selecting multiple elements on a table using AngularJS? In my table, the first column consists of checkboxes and I am interested in employing the SHIFT key along with mouse clicks to select several rows ...

What alternative can be used for jquery isotope when JavaScript is not enabled?

Is there a backup plan for jQuery isotope if JavaScript isn't working? For instance, if I'm using the fitColumns feature, is there an alternative layout style available in case JavaScript is disabled, similar to what is seen on the new Myspace? ...

The jQuery each function in combination with the index function allows for

I'm struggling to make this jQuery script work properly: $(document).on('knack-scene-render.scene_126', function() { $('#view_498 > div.kn-list-content.columns.is-multiline').each(function(index) { if ($(this).eq(inde ...

Assigning an identification number to specify the type of Chip

I am currently working on a project involving Material UI "Chips" that contain text and serve as references. Within the context of my project, I have Chips for both White Advantages and Black Advantages sections. However, there are instances where these Ch ...

Tips for resolving rendering page issues in an express app

My application is a straightforward blog platform that showcases a schema for the title, entry, and date of each blog post. There is also an edit/delete feature that is currently under development. When attempting to use the edit/delete button on a selecte ...

Create a regular expression that permits a sequence of numbers (either integer or decimal) arranged in groups of up to five, with each

Is it possible to create a regular expression that allows integers and decimals? var reg = /^((\s*)|([0-9]\d{0,9}(\.\d{1,3})?%?$))$/.; How can users input 0 to 5 groups of integers and decimals separated by |? Updated: This regex sh ...

Learning how to access my CSS file using Express and Node.js

I am new to using express and node.js. I am trying to develop my app, but for some reason, my style.css file is not being recognized and I am unsure why. Initially, I attempted to use .scss files, but after researching, I discovered that it was not possi ...

What causes special characters to be replaced when using the 'require' function in NodeJS?

I am a beginner in JavaScript and NodeJS, so please be patient with me if this issue seems obvious. The file I have outsourced is a simple config file. Here is an abbreviated version of it: config.js: var config = {}; config.Web = {}; config.Web.Title ...

Utilize Chrome storage instead of localstorage to generate Parse sessions

I'm currently developing a Chrome Extension that relies on Parse User sessions. Because localstorage is limited to specific domains, I am looking to utilize chrome.storage so the data can be accessed across any site. The existing Parse Javascript SDK ...

Issue with Bootstrap checkbox buttons not rendering properly

I'm attempting to utilize the checkbox button feature outlined on the bootstrap webpage here in the "checkbox" subsection. I copied and pasted the html code (displayed below) from that page into a jsfiddle, and checkboxes are unexpectedly appearing in ...