The HTMLCollection at index 0 has a list length of 0, attempting to access index [n] will result in an undefined value

Currently, I am creating numerous SVG elements with the help of leaflet and d3.js. My setup involves a leaflet map, followed by some divs below it, and then a script element where I am populating the map, incorporating data from .json files, and trying to associate event listeners with the divs to add and remove classes to the svg elements. While attempting to gather all the <path> elements that have been created so far to iterate through them and add a class, I seem to be facing difficulties in getting a for loop to function as desired.

    var lowlightGisUnfiltered = document.getElementById(mapDivId).getElementsByClassName("gisData");
    console.log("unfiltered",lowlightGisUnfiltered, "length", lowlightGisUnfiltered.length);

    var transfer = lowlightGisUnfiltered;
    console.log("transfer:", transfer, "length:", transfer.length);

    var llarray = Array.prototype.slice.call(lowlightGisUnfiltered);
    console.log(llarray);

    console.log(lowlightGisUnfiltered[1]);
    console.log(transfer.item(1));

    var lowlightGIS = [];
    for(var n = 0; n < lowlightGisUnfilteredArray.length; n++){
        console.log("test");
        if(llarray[n].classList.contains(selectorClass)) {

            lowlightGIS.push(lowlightGisUnfiltered[n])
            }
    }

The above code produces the following output:

  • unfiltered:[](a 580 element HTMLcollection that lists the length at the end as the correct length) length:0
  • transfer: [](a 580 element HTMLcollection that lists the length at the end as the correct length) length:0
  • [] (empty array)
  • undefined
  • null

All this code exists below the d3 and leaflet scripts where I am generating the dynamic tags.

I have reviewed several other questions related to HTMLcollections or NodeLists that deal with similar issues, but unfortunately, they did not provide any solutions.

edit: I also attempted using .querySelectorAll, but that only returned an empty array.

Answer №1

Here's how I found the solution:

After some trial and error, I discovered that d3.json works asynchronously. My mistake was placing my code outside of the d3.json function, which resulted in my data not being properly loaded.

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

Is it possible to manipulate the z-index programmatically?

I have been developing a Google Chrome extension that involves injecting HTML into webpages. The injected HTML should be displayed on top of the existing content, but I am encountering an issue. On some pages, the injected HTML does not show up, even after ...

Sending properties to a template literal within a loop

Currently, I am working on developing a dynamic select box. The challenge I am facing is in combining the row source data object with the string key or display name. Any thoughts or suggestions would be greatly appreciated. Thank you! const { rowSourceD ...

What are some ways to get Angular2 up and running in a newly created distribution directory?

Trying to setup my own Angular2+Typescript (+SystemJS+Gulp4) starter project has hit a roadblock for me. I encountered issues when transitioning from compiling TypeScript in the same folder as JavaScript with access to the node_modules folder, to organizin ...

Creating Backbone models that inherit the prototype from THREE.Object3D

I am looking to create a unique model that combines the functionality of Backbone.Model with another prototype from THREE.Object3D in three.js version r69. Currently, my approach involves creating an object and setting its prototype to be that of THREE.Obj ...

Ways to conceal various components while showcasing just a single element from every individual container

I am looking to only display specific span elements within their parent container (coin) while hiding the rest. The desired output should show only "1" and "first" while the other spans are hidden. <div class="types"> <div class=" ...

Styling elements with values from an object array

I have been working on a code snippet to extract checked checkboxes and match their names with an object array in order to retrieve certain values. You can find a sample fiddle here. Now, I am wondering how I can utilize these extracted values to dynamica ...

Preventing users from inputting the same number more than once

Here are a series of text input fields pertaining to a single question: <input type="text" name="{{ $answer->id }}" value="" style="width:20px; text-align:center" maxlength="1" oninput="this.value=this.value.replace(/[^0-5]/g,'');" /> & ...

Achieving repetitive progress bar filling determined by the variable's value

JSFiddle Here's a code snippet for an HTML progress bar that fills up when the "battle" button is clicked. I'm trying to assign a value to a variable so that the progress bar fills up and battles the monster multiple times based on that value. ...

Validating fields by combining jQuery

On my website, there are 3 select boxes allowing users to choose the day, month, and year. When the page loads, "Day" is displayed in the day select option and the name of the month (e.g., January) is displayed in the month: $("# ...

The context environment is failing to update the current state

Working with context in React can be tricky for some, including myself. I was hoping the new Context API would make things easier, but I'm still facing some issues. While I can get the initial value to display, the updates based on my Effect are not r ...

The Problem with TypeScript Union Types

I recently started using TypeScript and ran into an issue with a similar scenario. Despite my efforts, I encountered two errors that I can't seem to figure out. If anyone has any insights on how to resolve this, I would greatly appreciate the help! in ...

Delayed data binding in Angular 7 is causing issues

My current struggle involves Angular's data binding delay. After altering the value of this.notAvailable, the frontend doesn't update the [class.hide] until about 5 seconds after execution. Oddly enough, the console.log outputs appear promptly ...

Exploring modifications in axis for Google charts timeline

Can anyone help me figure out how to set my Google Timeline chart to always display 24 hours on the x-axis? Currently, it automatically changes based on the earliest and latest points, but I want it to consistently show all 24 hours. For example: ...

Using Angular 7 shared service to allow sibling components to exchange data between each other

In my Angular 7 application, I have two sibling components - a configurator component and a custom stepper component. The configurator component is responsible for fetching data from the API and performing calculations on it. I would like to display the ca ...

Trouble with retrieving JSON data?

Struggling to access the JSON object issue: Received JSON Object: {"71":"Heart XXX","76":"No Heart YYYY"} I attempted to retrieve values for 71 and 72 individually but encountered compile time problems as: Syntax error on token ".71", delete this token ...

Concealing/Revealing Elements with jquery

For hours, I've been attempting to switch between hiding one element and showing another in my script. Here is the code I am using: <script type="text/javascript"> function () { $('#Instructions').hide(); $('#G ...

Utilize modules within the AppModule to promote modularization and maintain separation of concerns in Angular 2

When using templates like those from the ASP.NET Core JavaScript services, typically a single module named AppModule is included. However, in my application, which is divided into two logical areas (AreaA and AreaB), I thought it would be better to use two ...

Regular expression: subpattern without immediate subsequent character

Consider a regular expression that needs to return true for any string containing the substring hello, followed by any string that does not start with ! or multiple instances of !. Here are some examples to clarify: var regExp = /someExpression/; regExp ...

Is NestJS the best choice for enforcing strong typing with TypeScript configurations?

My app has a main configuration expressed through environment variables (process.env). How can I expose it as one object using Next.js? In the code example below, I am able to retrieve values by keys. However, since I am passing a string, TypeScript is not ...

Evaluating QUnit Test Cases

How do you write a test method in QUnit for validating functions developed for a form? For example, let's consider a form where the name field should not be left blank. If the validation function looks like this: function validNameCheck(form) { if ...