Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
339 views
in Technique[技术] by (71.8m points)

javascript - How to change class for all elements retrieved by document.getElementsByClassName

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

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

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...