By cycero


2011-06-07 15:40:20 8 Comments

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

<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:

document.getElementByTokenId('14'); 

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

Thanks.

6 comments

@Ingo 2016-02-03 22:16:18

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;
};

@user1307434 2015-01-16 07:02:12

<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

@Felix Kling 2011-06-07 15:50:01

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:

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:

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 2011-06-07 16:05:37

+1 for the hard work, but bear in mind that children has a <IE9 quirk where it returns comment nodes and was only added to Firefox in version 3.5. childNodes with a nodeType check would be a "safer" approach. Also, hasAttribute() isn't supported by IE7 and lower. For those browsers, you'd have to do something like root.attributes.getNamedItem(attr).specified.

@Felix Kling 2011-06-07 16:08:16

@Andy: Uh, I did not know about these issues... thanks! I will leave it as exercise for the reader though ;)

@Andrei Cristian Prodan 2012-10-18 14:18:31

var element = document.querySelector('[tokenid="14"]'); --- not in safari 5.1.4

@Felix Kling 2012-10-18 15:14:25

@Andrei: Mmmh, according to caniuse.com it should be supported. Have you tried document.querySelector('[tokenid=14]') (value without quotation marks)?

@Bob van Luijt 2015-08-31 18:25:48

How is this done with Angular? ng-bind is custom too

@Thurloat 2011-06-07 15:45:43

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

    $('div[tokenid=14]')

as your selector.

@Briguy37 2011-06-07 15:45:20

You can accomplish this with JQuery:

$('[tokenid=14]')

Here's a fiddle for an example.

@sje397 2011-06-07 15:44:18

If you're willing to use JQuery, then:

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

Related Questions

Sponsored Content

93 Answered Questions

[SOLVED] How do I remove a particular element from an array in JavaScript?

  • 2011-04-23 22:17:18
  • Walker
  • 6253660 View
  • 7809 Score
  • 93 Answer
  • Tags:   javascript arrays

42 Answered Questions

[SOLVED] How do I remove a property from a JavaScript object?

27 Answered Questions

[SOLVED] What does "use strict" do in JavaScript, and what is the reasoning behind it?

58 Answered Questions

[SOLVED] How do I include a JavaScript file in another JavaScript file?

23 Answered Questions

[SOLVED] Get the current URL with JavaScript?

  • 2009-06-23 19:26:45
  • dougoftheabaci
  • 2745598 View
  • 2913 Score
  • 23 Answer
  • Tags:   javascript url

56 Answered Questions

[SOLVED] How do I check if an element is hidden in jQuery?

38 Answered Questions

[SOLVED] How do you get a timestamp in JavaScript?

86 Answered Questions

[SOLVED] How do JavaScript closures work?

4 Answered Questions

Sponsored Content