javascript 获取具有相同类的所有元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15340840/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get all elements with the same class
提问by Tbi45
I know that this:
我知道这个:
document.getElementsByClassName('class-1')[0].
selects the first <div>
that has the specify class.
选择<div>
具有指定类的第一个。
I guess using a for()
will get through the whole array of <div>
.
我想使用 afor()
将遍历整个<div>
.
Can somebody explain how to create that array ?
有人可以解释如何创建该数组吗?
I will prefer plain Js.
我会更喜欢普通的 Js。
回答by VisioN
Method getElementsByClassName()
returns a set of DOM elements that have a certain class name. Here is a canonical example of how to use the returned list of nodes:
方法getElementsByClassName()
返回一组具有特定类名的 DOM 元素。这是如何使用返回的节点列表的规范示例:
var elements = document.getElementsByClassName("class-1");
for (var i = 0, len = elements.length; i < len; i++) {
// elements[i].style ...
}