gpt4 book ai didi

javascript - 迭代 DOM 元素

转载 作者:行者123 更新时间:2023-11-28 19:03:00 25 4
gpt4 key购买 nike

我使用 for 循环迭代 DOM 元素,使用两种语法,并且在这两种语法中我得到了不同的结果。

JavaScript 方法 1 是

for (var sortable in document.getElementsByClassName('test')) {
console.log("---- " + sortable)
sortable.setAttribute('class', '');
}

此输出给出错误

undefined is not a function

对于 sortable.setAttribute('class', ''); 行。

并使用 javascript 2 方法

   var elements = document.getElementsByClassName("test");

for (var i=0; i< elements.length;i++) {
elements[i].setAttribute("class", "");
}

我得到了适当的结果。

我的html代码是

       <span class="test" id="test1">Test1 </span>
<span class="test" id="test2">Test2 </span>
<span class="test" id="test3">Test3 </span>

我不知道为什么我没有将 var sortable in document.getElementsByClassName('test') 中的 DOM 元素获取为 sortable

最佳答案

如果您在 JavaScript 中执行 for .. in 循环,请务必了解 for 循环返回的值实际上是键而不是值。

所以你可以尝试这个:

var testElements = document.getElementsByClassName('test');

for (var key in testElements) {
var sortable = testElements[key];
console.log("---- " + sortable)
sortable.setAttribute('class', '');
}

但是,这会失败,因为在 getElementsByClassName 返回的值上定义了许多属性,而并非所有属性都返回元素。

您可以通过执行以下操作来查看全部内容:

for (var key in document.getElementsByClassName('test')) {
console.log(key);
}

这将输出如下内容:

012test1test2test3lengthitemnamedItem

You can see that not only does the returned value contain the numerical indexes, it also has the ID's as properties and also an item and namedItem property.

Unfortunatety, your for-loop also doesn't work as you are changing the class name and getElementsByClassName returns a "live" collection, which means that once you change the class, it is removed from the collection.

You can work around this with a simple loop:

var elements = document.getElementsByClassName("test");

while (elements.length > 0) {
elements[0].setAttribute("class", "");
}

此解决方案取自:Javascript For Loop execution on dom element

关于javascript - 迭代 DOM 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32199386/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com