Kupto Kupto -4 years ago 133
HTML Question

How to correctly iterate through getElementsByClassName

I am Javascript beginner.

I am initing web page via the

, I have to find bunch of elements by their class name (
) and redistribute them into different nodes based on some logic. I have function
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++)

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

...this is my speculation...

...being changed inside function
(the DOM tree is being changed inside this function, and cloning of certain nodes happen).
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...


important fact I forgot to mention is that there might be one slide inside another, this is actually what changes the
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

Answer Source

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

nodeItem = nodeList.item(index)


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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download