使用JavaScript通过自定义属性获取元素 [英] Getting element by a custom attribute using JavaScript

查看:2633
本文介绍了使用JavaScript通过自定义属性获取元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个XHTML页面,其中每个HTML元素都有一个唯一的自定义属性,如下所示:

I have an XHTML page where each HTML element has a unique custom attribute, like this:

<div class="logo" tokenid="14"></div>

我需要一种通过ID查找此元素的方法,类似于文档。 getElementById(),但我想使用自定义tokenid属性来搜索元素,而不是使用通用ID。这样的事情:

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:

document.getElementByTokenId('14'); 

这可能吗?如果是的话 - 任何提示都会非常感激。

Is that possible? If yes - any hint would be greatly appreciated.

谢谢。

推荐答案

在HTML中使用自定义属性并不好。如果有的话,你应该使用 HTML5的数据属性

It is not good to use custom attributes in the HTML. If any, you should use HTML5's data attributes.

尽管如此,您可以编写自己的遍历树的函数,但与<<>相比 getElementById 因为你不能使用任何索引:

Nevertheless you can write your own function that traverses the tree, but that will be quite slow compared to getElementById because you cannot make use of any index:

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.

在较新的浏览器中,您使用 querySelector 方法,它只是:

In newer browsers you use of the querySelector method, where it would just be:

var element = document.querySelector('[tokenid="14"]');

这也会快得多。

更新:请注意@Andy E的评论如下。可能是你遇到IE的问题(一如既往;))。如果你做了很多这种元素检索,你真的应该考虑使用像jQuery这样的JavaScript库,就像其他人提到的那样。它隐藏了所有这些浏览器差异。

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.

这篇关于使用JavaScript通过自定义属性获取元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆