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

10
  • 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 ;) Commented Aug 25, 2015 at 7: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 Commented Aug 25, 2015 at 7:56
  • @Hammster Except that there are 3 elements... Commented Aug 25, 2015 at 7: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. Commented Aug 25, 2015 at 7:59
  • 1
    @Juhana NodeLists, like arrays, have 0 based indices... Commented Aug 25, 2015 at 7:59

1 Answer 1

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>

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.