cyc*_*ero 35 javascript getelementbyid
我有一个XHTML页面,其中每个HTML元素都有一个唯一的自定义属性,如下所示:
<div class="logo" tokenid="14"></div>
Run Code Online (Sandbox Code Playgroud)
我需要一种方法来通过ID找到这个元素,类似于document.getElementById(),但我不想使用通用ID,而是想使用我的自定义"tokenid"属性搜索元素.像这样的东西:
document.getElementByTokenId('14');
Run Code Online (Sandbox Code Playgroud)
那可能吗?如果是 - 任何提示都将非常感激.
谢谢.
Fel*_*ing 39
在HTML中使用自定义属性并不好.如果有的话,您应该使用HTML5的data属性.
不过,你可以编写自己的函数,遍历树,但是这将是非常缓慢相比,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;
}
Run Code Online (Sandbox Code Playgroud)
在最坏的情况下,这将遍历整棵树.考虑如何更改您的概念,以便尽可能地使用浏览器功能.
在较新的浏览器中,您使用的querySelector方法只是:
var element = document.querySelector('[tokenid="14"]');
Run Code Online (Sandbox Code Playgroud)
这也会快得多.
更新:请注意@Andy E的评论如下.可能是你遇到IE的问题(一如既往;)).如果你做了很多这种元素检索,你真的应该考虑使用像jQuery这样的JavaScript库,就像其他人提到的那样.它隐藏了所有这些浏览器差异.
小智 24
<div data-automation="something">
</div>
document.querySelector("div[data-automation]")
Run Code Online (Sandbox Code Playgroud)
=>找到div
document.querySelector("div[data-automation='something']")
Run Code Online (Sandbox Code Playgroud)
=>查找带有值的div
小智 5
如果你使用 jQuery,你可以使用他们的一些选择器魔法来做这样的事情:
$('div[tokenid=14]')
Run Code Online (Sandbox Code Playgroud)
作为您的选择器。
| 归档时间: |
|
| 查看次数: |
60792 次 |
| 最近记录: |