javascript Javascript通过其属性获取元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8396541/
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
Javascript to get elements by its attribute
提问by Jeyanth Kumar
<body>
<span someAttribute="xyz">.....</span>
...
<div>
...
<span someAttribute="abc">.....</span>
...
<div someAttribute="pqr">.....</div>
...
</div>
</body>
Here is a sample html page.. I need to select the html elements by its attributes i can get the attribute values by getAttribute()
but i need to select all the elements first.
这是一个示例 html 页面。我需要通过其属性来选择 html 元素,我可以获得属性值,getAttribute()
但我需要先选择所有元素。
How in javascript to get elements which has the attribute name as "someAttribute". Once i get the elements i can get the attribute values and use my function.
如何在 javascript 中获取属性名称为“someAttribute”的元素。一旦我获得元素,我就可以获得属性值并使用我的函数。
Note: i want to do this without using jquery.
注意:我想在不使用 jquery 的情况下执行此操作。
采纳答案by david
store each element in a array the loop throught each element, and if the element contains the attribute someAttribute do somgthing.
将每个元素存储在一个数组中,循环遍历每个元素,如果元素包含属性 someAttribute,则执行某些操作。
var arr_elms = [];
arr_elms = document.body.getElementsByTagName("*");
var elms_len = arr_elms.length;
for (var i = 0; i < elms_len; i++) {
if(arr_elms[i].getAttribute("someAttribute") != null){
alert("FOUND : " + arr_elms[i].getAttribute("someAttribute"));
}
}
回答by RedPoppy
In new browsers you can do:
在新浏览器中,您可以执行以下操作:
var el = document.querySelector('[someAttribute="someValue"]');
回答by I need an IPhone.
You can traver all elements of DOM tree.
您可以遍历 DOM 树的所有元素。
回答by Romi Halasz
You can select elements by tag name using document.body.getElementsByTagName("div")
to get all the div elements inside your document. This function returns an array of elements, which you can parse and filter out elements that don't match your criteria.
您可以通过标签名称选择元素,document.body.getElementsByTagName("div")
用于获取文档中的所有 div 元素。此函数返回一个元素数组,您可以解析和过滤掉与您的条件不匹配的元素。
回答by pkyeck
you can use
您可以使用
var all = document.getElementsByTagName('*');
but this also returns the html
, head
and body
...
但这也会返回html
,head
和body
...
and then do a loop over all elements and look for the attributes.
然后对所有元素进行循环并查找属性。
回答by Irvin Dominin
I found a snippet called getElementsByAttribute(doc, tagArray, attribute, attributeValue)
我发现了一个名为 getElementsByAttribute(doc, tagArray, attribute, attributeValue)
You can give a try to a working fiddle: http://jsfiddle.net/Yx7EU/
你可以尝试一个工作小提琴:http: //jsfiddle.net/Yx7EU/
Hope this can help.
希望这能有所帮助。