Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a table which contains 3 rows. Each row has the class: .myClass.

I then query for the table rows with document.getElementsByClassName('myClass') and iterate over the elements, changing each row's class to .otherClass.

However,

console.log(document.getElementsByClassName('otherClass'))

only returned one row.

And, when I looked at the DOM, only the first .myClass row had its class changed to .otherClass; the other remained untouched.

How can I change the class of all .myClass rows to .otherClass?

var c = document.getElementsByClassName('myTable')[0];
var x = c.getElementsByClassName('myClass');

for (var i = 0; i < x.length; i++) {
  x[i].className = 'otherClass';
}

x = c.getElementsByClassName('otherClass');

console.log(x);  // only one element
<table class="myTable">
  <tr class="myClass2">
    <td>Content</td>
    <td>Content</td>
  </tr>
  <tr class="myClass">
    <td>Content</td>
    <td>Content</td>
  </tr>
  <tr class="myClass">
    <td>Content</td>
    <td>Content</td>
  </tr>
</table>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
333 views
Welcome To Ask or Share your Answers For Others

1 Answer

getElementsByClassName, like other HTML collections, is "live", that is, when you assign another class name to its member, it's removed from the collection on the fly and its length gets decremented. That's why your loop runs only once.

var x = document.getElementsByClassName('myClass');
alert("before: " + x.length);
x[0].className='otherClass';  
alert("after: " + x.length);
.myClass { color: black }
.otherClass { color: red }
<b class="myClass">hi</b>
<b class="myClass">hi</b>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...