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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…