Skip to content
Advertisement

How to correctly iterate through getElementsByClassName

I am Javascript beginner.

I am initing web page via the window.onload, I have to find bunch of elements by their class name (slide) and redistribute them into different nodes based on some logic. I have function Distribute(element) which takes an element as input and does the distribution. I want to do something like this (as outlined for example here or here):

var slides = getElementsByClassName("slide");
for(var i = 0; i < slides.length; i++)
{
   Distribute(slides[i]);
}

however this does not do the magic for me, because getElementsByClassName does not actually return array, but a NodeList, which is…

…this is my speculation…

…being changed inside function Distribute (the DOM tree is being changed inside this function, and cloning of certain nodes happen). For-each loop structure does not help either.

The variable slides act’s really un-deterministicaly, through every iteration it changes it’s length and order of elements wildly.

What is the correct way to iterate through NodeList in my case? I was thinking about filling some temporary array, but am not sure how to do that…

EDIT:

important fact I forgot to mention is that there might be one slide inside another, this is actually what changes the slides variable as I have just found out thanks to user Alohci.

The solution for me was to clone each element into an array first and pass the array ono-by-one into Distribute() afterwards.

Advertisement

Answer

According to MDN, the way to retrieve an item from a NodeList is:

nodeItem = nodeList.item(index)

Thus:

var slides = document.getElementsByClassName("slide");
for (var i = 0; i < slides.length; i++) {
   Distribute(slides.item(i));
}

I haven’t tried this myself (the normal for loop has always worked for me), but give it a shot.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement