Javascript For dom元素上的循环执行 [英] Javascript For Loop execution on dom element
问题描述
我有javascript代码来获取带有类名的元素并迭代从元素中删除类。
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","");
}
并且有3个范围,类名为test。 HTML代码
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>
但是我只删除了2个课程。第二个跨度类仍然存在。
But I am getting only 2 class removed. The second span class still remains there.
控制台输出
长度3
Length 3
---- 0
---- 1
推荐答案
getElementsByClassName 返回实时 HTMLCollection 对象,从元素中删除类时会更新。
getElementsByClassName returns a live HTMLCollection object, which gets updated when you remove the class from the elements.
因此,您可以使用的一个简单逻辑是使用while循环并查看是否该集合包含任何项目,如果是这样,则从第一项中删除该类。
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>
这篇关于Javascript For dom元素上的循环执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!