使用 JavaScript 通过自定义属性获取元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6267816/
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
Getting element by a custom attribute using JavaScript
提问by cycero
I have an XHTML page where each HTML element has a unique custom attribute, like this:
我有一个 XHTML 页面,其中每个 HTML 元素都有一个唯一的自定义属性,如下所示:
<div class="logo" tokenid="14"></div>
I need a way to find this element by ID, similar to document.getElementById()
, but instead of using a general ID, I want to search for the element using my custom "tokenid"
attribute. Something like this:
我需要一种通过 ID 查找此元素的方法,类似于document.getElementById()
,但我想使用自定义"tokenid"
属性搜索该元素,而不是使用通用 ID 。像这样的东西:
document.getElementByTokenId('14');
Is that possible? If yes - any hint would be greatly appreciated.
那可能吗?如果是 - 任何提示将不胜感激。
Thanks.
谢谢。
回答by Felix Kling
It is not good to use custom attributes in the HTML. If any, you should use HTML5's data
attributes.
在 HTML 中使用自定义属性并不好。如果有的话,你应该使用HTML5 的data
属性。
Nevertheless you can write your own function that traverses the tree, but that will be quite slowcompared to getElementById
because you cannot make use of any index:
尽管如此,您可以编写自己的遍历树的函数,但这与您无法使用任何索引相比会很慢getElementById
:
function getElementByAttribute(attr, value, root) {
root = root || document.body;
if(root.hasAttribute(attr) && root.getAttribute(attr) == value) {
return root;
}
var children = root.children,
element;
for(var i = children.length; i--; ) {
element = getElementByAttribute(attr, value, children[i]);
if(element) {
return element;
}
}
return null;
}
In the worst case, this will traverse the whole tree. Think about how to change your concept so that you can make use browser functions as much as possible.
在最坏的情况下,这将遍历整棵树。想想如何改变你的概念,以便尽可能地使用浏览器功能。
In newer browsers you use of the querySelector
method, where it would just be:
在较新的浏览器中,您使用该querySelector
方法,它只是:
var element = document.querySelector('[tokenid="14"]');
This will be much faster too.
这也会快得多。
Update:Please note @Andy E's comment below. It might be that you run into problems with IE (as always ;)). If you do a lot of element retrieval of this kind, you really should consider using a JavaScript library such as jQuery, as the others mentioned. It hides all these browser differences.
更新:请注意下面@Andy E 的评论。可能是您遇到了 IE 的问题(一如既往;))。如果您进行大量此类元素检索,您真的应该考虑使用 JavaScript 库,例如 jQuery,正如其他人提到的那样。它隐藏了所有这些浏览器差异。
回答by user1307434
<div data-automation="something">
</div>
document.querySelector("div[data-automation]")
=> finds the div
=> 找到 div
document.querySelector("div[data-automation='something']")
=> finds the div with a value
=> 找到具有值的 div
回答by Thurloat
If you're using jQuery, you can use some of their selector magic to do something like this:
如果你使用 jQuery,你可以使用他们的一些选择器魔法来做这样的事情:
$('div[tokenid=14]')
as your selector.
作为您的选择器。
回答by sje397
回答by Briguy37
回答by Ingo
Use this more stable Function:
使用这个更稳定的函数:
function getElementsByAttribute(attr, value) {
var match = [];
/* Get the droids we are looking for*/
var elements = document.getElementsByTagName("*");
/* Loop through all elements */
for (var ii = 0, ln = elements.length; ii < ln; ii++) {
if (elements[ii].nodeType === 1){
if (elements[ii].name != null){
/* If a value was passed, make sure it matches the elements */
if (value) {
if (elements[ii].getAttribute(attr) === value)
match.push(elements[ii]);
} else {
/* Else, simply push it */
match.push(elements[ii]);
}
}
}
}
return match;
};