首页 > 解决方案 > 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/

标签: javascriptarraysconsolenodelist

解决方案


您的控制台语句甚至在获取数据之前就已执行。我将它们链接在另一个“then”函数(承诺链接)中,如下所示。这样,您的控制台语句在您的结果被解析为 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);
  })
}

推荐阅读