Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find an element in DOM based on an attribute value

Tags:

javascript

dom

Can you please tell me if there is any DOM API which search for an element with given attribute name and attribute value:

Something like:

doc.findElementByAttribute("myAttribute", "aValue"); 
like image 243
michael Avatar asked Apr 22 '10 21:04

michael


People also ask

How do I select a DOM element with a data attribute?

Use the querySelector method to get an element by data attribute, e.g. document. querySelector('[data-id="box1"]') . The querySelector method returns the first element that matches the provided selector or null if no element matches the selector in the document.

How can we find an element in DOM?

The easiest way to find an HTML element in the DOM, is by using the element id.

How do you check if a DOM element has an attribute?

HTML DOM Element hasAttribute() The hasAttribute() method returns true if the attribute exists, otherwise false .


2 Answers

Modern browsers support native querySelectorAll so you can do:

document.querySelectorAll('[data-foo="value"]'); 

https://developer.mozilla.org/en-US/docs/Web/API/Document.querySelectorAll

Details about browser compatibility:

  • http://quirksmode.org/dom/core/#t14
  • http://caniuse.com/queryselector

You can use jQuery to support obsolete browsers (IE9 and older):

$('[data-foo="value"]'); 
like image 198
Wojtek Kruszewski Avatar answered Sep 19 '22 09:09

Wojtek Kruszewski


Update: In the past few years the landscape has changed drastically. You can now reliably use querySelector and querySelectorAll, see Wojtek's answer for how to do this.

There's no need for a jQuery dependency now. If you're using jQuery, great...if you're not, you need not rely it on just for selecting elements by attributes anymore.


There's not a very short way to do this in vanilla javascript, but there are some solutions available.

You do something like this, looping through elements and checking the attribute

If a library like jQuery is an option, you can do it a bit easier, like this:

$("[myAttribute=value]") 

If the value isn't a valid CSS identifier (it has spaces or punctuation in it, etc.), you need quotes around the value (they can be single or double):

$("[myAttribute='my value']") 

You can also do start-with, ends-with, contains, etc...there are several options for the attribute selector.

like image 37
Nick Craver Avatar answered Sep 17 '22 09:09

Nick Craver