Javascript 如何使用getElementsByClassName获取具有特定类的所有标记?
我希望警报会给我Javascript 如何使用getElementsByClassName获取具有特定类的所有标记?,javascript,html,dom,Javascript,Html,Dom,我希望警报会给我[object HTMLCollection],然后只给两个元素,它们具有class=“dropdowntextbox”。这种行为的原因是什么?for..in迭代给定对象的属性。也就是说,您正在迭代HTMLCollectionproperties 您需要使用Array.from将整个HTMLCollection转换为常规数组,并使用Array.prototype.forEach: [object HTMLCollection] 0 1 length item namedItem
[object HTMLCollection]
,然后只给两个
元素,它们具有class=“dropdowntextbox”
。这种行为的原因是什么?for..in
迭代给定对象的属性。也就是说,您正在迭代HTMLCollection
properties
您需要使用Array.from
将整个HTMLCollection
转换为常规数组,并使用Array.prototype.forEach
:
[object HTMLCollection]
0
1
length
item
namedItem
此外,如果您在ES2015+环境中,您可以使用for..of
:
Array.from(document.getElementsByClassName("dropdowntextbox")).forEach(el => {
})
您正在使用一个
for..in
循环,它迭代对象的可枚举属性名——这将为您提供对象的所有属性,在本例中是一个HTMLCollection(而不是一个可以为您提供预期行为的数组)
通过使用for..of
循环,它将使用特定于对象的迭代方法,循环遍历迭代器生成的值;在这种情况下,你的3个div
for(let el of Array.from(document.getElementsByClassName("dropdowntextbox"))) {
}
这是因为HTMLCollection实际上是一个对象,您可以通过日志记录看到这一点
for (let div of document.getElementsByClassName("dropdowntextbox")){
alert(div.toString());
}
那么你的。。在对象关键点之间循环。
要实际循环HTML对象,可以使用以下命令将HTMLCollection转换为数组:
typeof document.getElementsByClassName("dropdowntextbox");
然后像往常一样骑自行车
var nodes = Array.from(document.getElementsByClassName("dropdowntextbox"));
for(变量i=0;i
在“for”循环中,循环浏览HTMLCollection对象的属性
你应该这样做:
for(var i = 0; i < nodes.length; i++){
//use nodes[i]
}
var collection=document.getElementsByClassName(“dropdowntextbox”);
对于(x=0;x
此处测试:
你好
var tags=document.getElementsByClassName(“dropdowntextbox”);
对于(var i=0;i
for的循环可以处理HTMLCollection。因此,无需将其转换为数组。只需使用(document.getElementsByClassName(“dropdowntextbox”)中的div{console.log(div,document.getElementsByClassName(“dropdowntextbox”);}即可查看此输出的含义!迭代项目端注意:如果您学会了如何使用调试而不是警报,您就可以自己动手了。这是最简单的方法
for(var i = 0; i < nodes.length; i++){
//use nodes[i]
}
var collection = document.getElementsByClassName("dropdowntextbox");
for(x = 0; x < collection.length; x++)
{
alert(collection[x].innerHtml);
}