Jump to content

Noob question: getElementsByClassName does not include all divs?


Emwat Oon
 Share

Recommended Posts

It gets all elements, but the list that it returns is a "live" list. That means that if you change the class of an element, it will get removed from that list. So you're skipping every other element. You change the first one, and then it gets removed, and the second one becomes the first one and the third one becomes the second one. Then when you try to change the second item in the list you're changing the third element that was originally returned.You can either loop backwards through the array, or use a while loop instead of a for loop.

for (var i = div.length - 1; i >= 0 ; i--) {
or
while ((i = div.length - 1) >= 0) {
  • Like 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...