Cannot pass through chrome nodelist

I am developing a chrome extension and have a nodelist type problem.

var compoentChange = document.getElementById("component_change");
var items = compoentChange.getElementsByTagName("option");

      

When I am console.log(items)

, he shows [item: function]

. When I expand it, it has all the option elements and a length property.

The problem is that I cannot access these items. When I am console.log(items.length)

, I receive undefined

.

How do I iterate through a variable items

?

for(i in items){}

and the for

loop doesn't work.

+3


source to share


5 answers


You can still do items.length

, so just create a for loop like this. I suggest inserting it into an array.

var myArray = [];

for(var i=0; i<items.length; i++){
     myArray.push(items[i]);
}

      



Ok, if that's not an option, try something like this:

var myArray = [];
for(var i=0, e=1; i<e; i++ ){
   if(items[i] != undefined){
      e++;
      myArray.push(items[i]);
   }else{
      break;
   }
}

      

+2


source


NodeLists are array-like objects. You can iterate with a regular loop for

(not for..in

):

for (var i = 0; i < items.length; i++) { ... }

      



Or you can convert this array-like object to a real array and use your own array methods on it:

[].forEach.call(items, function(item) { ... });

      

+1


source


If you are logging two during pageload, the reason you can use console.log () NodeList

, but not the attribute length

, is because it NodeList

is a "live" collection. Both are undefined until the DOM finishes loading, but since it NodeList

is in real time, it will update in the Chrome console. The attribute length

was undefined when it was registered and because it doesn't live it will stay undefined

in the console.

You can set a variable to reference the nodeList at any time, but wait for the DOM to be ready before trying to use the data (using a function, document.ready

or perhaps document.addEventListener()

).

+1


source


I met a similar problem with you. It turns out this is because I have to access the data after the DOM has finished loading.

document.addEventListener("DOMContentLoaded", function () {
    divs = document.getElementsByTagName("div");
    console.log(divs);
}, false);

      

0


source


for ... of can be used for this situation. However, due to a bug , this feature cannot be used on chrome.

0


source







All Articles