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.
source to share
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;
}
}
source to share
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()
).
source to share