0

With this code I am looping through the li elements to add the class 'cool'. Just testing different methods such as getElementById and querySelectorAll and they work fine, but when I use getElementsByClassName, it skips every other one out, not applying the style to it. I removed the i++ counter which applies it to every element, but wouldn't that lead to an infinite loop? Can anyone explain?

var listItems = document..getElementsByClassName('test');

var i;
for (i = 0; i < listItems.length; i++) { //loop through elements //remove ++ when using .getElementsByClassName method to select each element
listItems[i].className = 'cool';// change class to cool
}
Patrick McDermott
  • 1,220
  • 1
  • 15
  • 30
  • Isn't it because you have `document..getElementsByClassName('test');` with two **dots** instead of one? This would basically fail to execute and so the class wouldn't be added. Check your browser console (F12 on chrome) – Vadorequest Nov 11 '15 at 10:38
  • why do you think it would cause an infinite loop – sahbeewah Nov 11 '15 at 10:39
  • 1
    Sounds like it might be live nodelist issue. If you change the class name that element gets removed from the nodelist - therefore the loop skips over the next one. – Andy Nov 11 '15 at 10:39
  • 1
    the reason is `getElementsByClassName` returns a live list that will change if you change classname property of the element,one solution is looping backwards – maioman Nov 11 '15 at 10:41
  • @sahbeewah If he removes the `i++` then yes, the counter `i` won't increment anymore and therefore the loop will never end. If the code is executed, but I believe it would. (Meaning it's not a syntax error not to add the `i++` at the end) – Vadorequest Nov 11 '15 at 10:41
  • 2
    When you change a class of an item, it is removed from this list, and all items slide left. So, after increasing `i` to 1, you actually access the **third** element, but not the **second**. – Yeldar Kurmangaliyev Nov 11 '15 at 10:41
  • 2
    @Vadorequest If he removes `++`, it will work properly. The loop will end, because he will remove all items of this class, and node list will become empty. – Yeldar Kurmangaliyev Nov 11 '15 at 10:42
  • Ah, right, even though you made a *copy* using `listItems`, since it's a copy by reference (because it's an object) then the copy would be altered on live. So @YeldarKurmangaliyev explanation is right. Another way going forward would be to `JSON.parse(JSON.stringify(document.getElementsByClassName('test');))` so you get a copy by value and not by reference and you can use the `i++`. – Vadorequest Nov 11 '15 at 10:44
  • Thanks guys! Appreciate all input – Patrick McDermott Nov 11 '15 at 10:51

0 Answers0