javascriptarraysconsolenodelist

Why does my nodelist contain 0 items when console logged from my JS file?


The JS code that I'm concerned with is this:

 const modals=document.querySelectorAll('.modal');
    const modalsArray=[...modals];
    console.log(modalsArray);
    
    document.addEventListener('click', function (e) {
      e.stopPropagation();
      e.preventDefault();
      if (e.target.classList.contains("item")) {
        itemIndex=e.target.classList.item(1);
        const modals=document.querySelectorAll('.modal');
        const modalsArray=[...modals];
        console.log(itemIndex);
        console.log(modalsArray);
        modalsArray.filter(function (modal) {
          if (modal.classList.item(1)===itemIndex) {
            modal.classList.add('on');
            modalContainer.classList.remove('off');
            modalContainer.classList.add('on');
          }
        })
      }
    });


const arrow=document.querySelectorAll('.arrow');
const arrowArray=[...arrow];
console.log(arrowArray);

Whenever I console log the modalsArray or the arrowArray from my JS file, the array shows up empty. But I found that if I write out the code from scratch in the console to make the arrays, then all the items in the array show up properly.

So why is this happening? Why is an empty array currently showing up on my console? Does it have to do with scope or something?

When I put the modalsArray inside the eventlistener, and I click the respective target, an array will show properly and the rest of the code in that eventlistener works properly.

I'm noticing the same thing with the arrowArray and realized these two elements are having the same problem. I figured I should ask then because something is definitely up.

So why is an empty array showing up for both of these elements as seen in the image?

enter image description here

Check out my fiddle for more information: https://jsfiddle.net/apasric4/kvs25wbL/3/


Solution

  • Your console statements are executing even before the data is fetched. I chained them in another "then" function (promise chaining) as follows. This way your console statements run after your results are parsed to hmtl.

    https://jsfiddle.net/v83zqofp/1/

    function generateHTML (data) {
      fetchData(data)
      .then(function(data){
        let results=data.results;
        return results.map(function(result,index){
          -------------
          main.lastElementChild.insertAdjacentHTML('afterend', html);
          modalContainer.insertAdjacentHTML('beforeend', overlayHtml);      
        })
      }).then (function (data) {
          const modals=document.querySelectorAll('.modal');
          const modalsArray=[...modals];
          console.log(modalsArray);
    
          const arrow=document.querySelectorAll('.arrow');
          const arrowArray=[...arrow];
          console.log(arrowArray);
      })
    }