Getting element by a custom attribute using JavaScript

JavascriptGetelementbyid

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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

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

You can accomplish this with JQuery:

$('[tokenid=14]')

Here's a fiddle for an example.

Solution 5 - Javascript

If you're willing to use JQuery, then:

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

Solution 6 - Javascript

Doing this with vanilla JavaScript will do the trick:

  const something = document.querySelectorAll('[data-something]')

Solution 7 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioncyceroView Question on Stackoverflow
Solution 1 - JavascriptFelix KlingView Answer on Stackoverflow
Solution 2 - Javascriptuser1307434View Answer on Stackoverflow
Solution 3 - JavascriptThurloatView Answer on Stackoverflow
Solution 4 - JavascriptBriguy37View Answer on Stackoverflow
Solution 5 - Javascriptsje397View Answer on Stackoverflow
Solution 6 - JavascriptAnthony HellbergView Answer on Stackoverflow
Solution 7 - JavascriptIngoView Answer on Stackoverflow