1

I've been trying to iterate over a NodeListOf<HTMLElement> . I can get the NodeList but not iterate over it using methods.

When I try examples from other stackoverflow questions or mdn web docs, they work but only when I iterate over the Nodelist in the same javascript file it was created.

The following code and the ones in the comments work, but not when I try to get at the nodelist which was written in main.js from another file called drawer.js . So it seems like that's what the problem is, and other stackoverflow questions don't specify if they are having problems across files.

The nodelist comes from these elements in main.js:

    const Bars = az.map((element, i) =>
        
        (   
            <div name="barHolder" className="barHolder" >
                <div className="bar" key={element} id={element} onClick={() => clickedBar(element, i)} > 
                    <div>{element}</div>
                        { element === viewAvailable && (
                            barInfo(element) 
                        )}
                </div>            
            </div>    
        )
    )

in drawer.js:

const barTags = document.getElementsByName('barHolder')

barTags.addEventListener("click", () => { console.log("clicked")}

another way:

barTags.forEach(
    function () {
        console.log("ffs");
    },
'myThisArg'
);  

and using jquery after making the elements I wanted to select into a list:

$( document ).ready(function() {

    $( "li" ).each(function( index ) {
        console.log( "clicked");
    });
    
});

When run const List = document.getElementById("list") in main.js, it works. When I run the code from drawer.js, I get Uncaught TypeError: e is null.

I'm trying to reach the NodeList because I would like add an event listener so that when they are clicked, it swipes down the drawer they are in.

This is using preact and parcel. The drawer is Material Ui /MUI

Winni
  • 31
  • 3
  • Is `className` for `class` attribute? you can use class for it. – Hardik Solanki Jan 05 '23 at 09:09
  • You can use `for-of` on the `NodeList` from `querySelectorAll`: ```for (const element of document.querySelectorAll(`[name="barHolder"]`)) { /* ... */ }```. See also [my answer here](https://stackoverflow.com/a/9329476/157247), which covers looping "array-like" things such as `NodeList` and `HTMLCollection` objects. – T.J. Crowder Jan 05 '23 at 09:11
  • Thanks, @HardikSolanki and @T.J. Crowder Yes these things work in my main.js, where the elements I'm trying to call are. But, when I try to run them or `const barTags = document.getElementById("routeList").childNodes` or the above code from the drawer.js file where my drawer is, it says that the node is null. I'm thinking I'm missing something about accessing nodeLists across files. – Winni Jan 05 '23 at 17:19

0 Answers0