[英]In Javascript how do I iterate the results of getElementsByClassName() and modify display attribute
How do I iterate the results of getElementsByClassName()
我如何迭代
getElementsByClassName()
的结果
This is what I had: 这就是我所拥有的:
function togglePotentialMatchesLinks()
{
alert("fred");
var els = document.getElementsByClassName("releasegroupingpotential");
var e;
for(e in els)
{
e.style.display = e.style.display=="none"
?"table-row-group"
:"none";
}
return true;
}
I have since read its not actually an array but a NodeList
or a HtmlCollection
, but that has left me none the wiser how to modify the function so that it works. 从那以后,我读到的实际上不是一个数组,而是一个
NodeList
或HtmlCollection
,但这使我没有更明智的方法来修改该函数以使其起作用。
Update 更新资料
Now working based on Trandences answer 现在基于Trandences回答工作
function togglePotentialMatchesLinks()
{
var els = document.getElementsByClassName("releasegroupingpotential");
var e;
for (var i = 0; i < els.length; ++i) {
e = els[i];
e.style.display = e.style.display=="none"
?"table-row-group"
:"none";
}
return true;
}
Per the docs: https://developer.mozilla.org/en-US/docs/Web/API/NodeList 根据文档: https : //developer.mozilla.org/zh-CN/docs/Web/API/NodeList
for (var i = 0; i < myNodeList.length; ++i) {
var item = myNodeList[i]; // Calling myNodeList.item(i) isn't necessary in JavaScript
}
Yes, it's a NodeList but that's OK. 是的,这是一个NodeList,但是没关系。 You can check for a number of properties to accomplish your goal, such as
collection.item && collection.length
. 您可以检查许多属性来实现您的目标,例如
collection.item && collection.length
。 Here is a way to do it: http://jsbin.com/bajomi/1/edit?js,output 这是一种实现方法: http : //jsbin.com/bajomi/1/edit?js,输出
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.