如何更改由document.getElementsByClassName检索的所有元素的类 [英] How to change class for all elements retrieved by document.getElementsByClassName
问题描述
.myClass
。然后我用 document.getElementsByClassName('myClass')
并迭代元素,将每行的类更改为 .otherClass
。 然而,
console.log(document.getElementsByClassName('otherClass'))
只返回一行。
看着DOM,只有第一个 .myClass
行的类更改为 .otherClass
;另一个保持不变。
如何将所有 .myClass
行的类更改为 .otherClass
?
< table class =myTable > < tr class =myClass2> < TD>内容< / TD> < TD>内容< / TD> < / TR> < tr class =myClass> < TD>内容< / TD> < TD>内容< / TD> < / TR> < tr class =myClass> < TD>内容< / TD> < TD>内容< / TD> < / tr>< / table>
var x = document.getElementsByClassName('myClass'); alert(before:+ x。长度); X [0机] .className = 'otherClass'; alert(after:+ x.length);
.myClass {color:black} .otherClass {color:red}
< b class =myClass> hi< / b>< b class =myClass> hi< / b>
文档:
HTML DOM中的HTMLCollection是直播的;它会在底层文档发生更改时自动更新。
你的问题,你可以设置第一个元素的className,直到集合中没有剩下的元素:
while(x.length > 0){
x [0] .className ='otherClass';
}
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>
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>
Docs:
An HTMLCollection in the HTML DOM is live; it is automatically updated when the underlying document is changed.
To answer in context to your question, you could set the className of the first element until there are none left in the collection:
while(x.length > 0) {
x[0].className = 'otherClass';
}
这篇关于如何更改由document.getElementsByClassName检索的所有元素的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!