3

I have javascript code to get the elements with class name and iterate over that remove the class from elements.

  var elements = document.getElementsByClassName("test");
       console.log("Length " + elements.length)
        for (var i=0; i< elements.length;i++) {
               console.log("---- "+i)
               elements[i].setAttribute("class","");
         }

and there are 3 span with the class name "test". HTML code is

<span class="test" id="test1">Test1 </span>
<span class="test" id="test2">Test2 </span>
<span class="test" id="test3">Test3 </span>

But I am getting only 2 class removed. The second span class still remains there.

The console output is

Length 3

---- 0

---- 1

Community
  • 1
  • 1
Anita
  • 2,352
  • 2
  • 19
  • 30
  • 1
    i < elements.length in this case i < 2 will only give you 0,1 you'll need to use <= (lower and equal) to get 3 values ;) – Hans Koch Aug 25 '15 at 07:56
  • 8
    `getElementsByClassName` returns a *live list*. Changing the class will remove the elements from the list. You need to make a copy of them somehow before removing them – CodingIntrigue Aug 25 '15 at 07:56
  • @Hammster Except that there are 3 elements... – JJJ Aug 25 '15 at 07:57
  • @RGraham: Or, more efficiently, process them back to front. This way, you are already finished with the part of the collection that gets disturbed. – Amadan Aug 25 '15 at 07:59
  • 1
    @Juhana NodeLists, like arrays, have 0 based indices... – danwellman Aug 25 '15 at 07:59
  • @danwellman `elements.length` is 3 no matter what based indices you use. – JJJ Aug 25 '15 at 08:00
  • @Amadan Yup, also an option. – CodingIntrigue Aug 25 '15 at 08:01
  • @Juhana you don't use the length to get the elements, you use the index. In a NodeList of 3 elements, elements[3] === undefined – danwellman Aug 25 '15 at 08:15
  • @danwellman Look, Hammster said "i < elements.length in this case i < 2" which is wrong because `elements.length` is 3, not 2. We're talking about the list length here. No-one has said anything about `elements[3]`. – JJJ Aug 25 '15 at 08:22
  • @juhana is right i messed up ;) – Hans Koch Aug 25 '15 at 08:28

1 Answers1

10

getElementsByClassName returns a live HTMLCollection object, which gets updated when you remove the class from the elements.

So one simple logic you can use is to use a while loop and see if the collection has any items, if so remove the class from the first item.

function removeClass() {
  var elements = document.getElementsByClassName("test");
  console.log("Length " + elements.length)
  while (elements.length) {
    elements[0].setAttribute("class", "");
  }
}
.test {
  color: red;
}
<span class="test" id="test1">Test1 </span>
<span class="test" id="test2">Test2 </span>
<span class="test" id="test3">Test3 </span>
<button onclick="removeClass()">Test</button>
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531