CandyPaintedRIMS
CandyPaintedRIMS

Reputation: 179

Unable to use .length with a NodeList

I am attempting to find elements that have a certain class and make an array of their IDs.

var youtubeVids = document.getElementsByClassName('youtube');
var ytVidIds = [];
for(i = 0; i < youtubeVids.length; i++) {
    ytVidIds[i] = jQuery(youtubeVids[i]).attr('id');
}

I can see the correct array of elements in the console if I use:

console.log( youtubeVids );

However, I get a value of '0' when I use:

console.log( youtubeVids.length );

This tiny little bug is destroying the functionality of my entire site! Please offer some wisdom if you can see what I'm doing wrong.

edit: Heres the HTML

<div class='youtube' id='slide_0'></div>
<div id='slide_1'></div>
<div id='slide_2'></div>

Upvotes: 1

Views: 1038

Answers (1)

curveball
curveball

Reputation: 4505

well, try the following:

var youtubeVids = Array.prototype.slice.call(document.getElementsByClassName('youtube'));

In case your live collection eventually gets altered, the real array is always there for you.

Upvotes: 1

Related Questions