Monday, May 20, 2024
82
rated 0 times [  83] [ 1]  / answers: 1 / hits: 123867  / 13 Years ago, tue, june 7, 2011, 12:00:00

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.


More From » getelementbyid

 Answers
17

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.


[#91829] Sunday, June 5, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tomas

Total Points: 165
Total Questions: 111
Total Answers: 103

Location: Maldives
Member since Tue, Dec 21, 2021
2 Years ago
tomas questions
Thu, Jan 27, 22, 00:00, 2 Years ago
Mon, May 10, 21, 00:00, 3 Years ago
Tue, Jan 5, 21, 00:00, 3 Years ago
;