Skip to content Skip to sidebar Skip to footer

Getting Element By A Custom Attribute Using Javascript

I have an XHTML page where each HTML element has a unique custom attribute, like this: I need a way to find this element by ID, s

Solution 1:

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

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:

functiongetElementByAttribute(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;
        }
    }
    returnnull;
}

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:

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.

Solution 2:

<div data-automation="something">
</div>

document.querySelector("div[data-automation]")

=> finds the div

document.querySelector("div[data-automation='something']")

=> finds the div with a value

Solution 3:

If you're using jQuery, you can use some of their selector magic to do something like this:

    $('div[tokenid=14]')

as your selector.

Solution 4:

If you're willing to use JQuery, then:

var myElement = $('div[tokenid="14"]').get();

Solution 5:

You can accomplish this with JQuery:

$('[tokenid=14]')

Here's a fiddle for an example.

Post a Comment for "Getting Element By A Custom Attribute Using Javascript"