Find an element in DOM based on an attribute value
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"]');
We can use attribute selector in DOM by using document.querySelector()
and document.querySelectorAll()
methods.
for yours:
document.querySelector("[myAttribute='aValue']");
and by using querySelectorAll()
:
document.querySelectorAll("[myAttribute='aValue']");
In querySelector()
and querySelectorAll()
methods we can select objects as we select in "CSS".
More about "CSS" attribute selectors in https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors
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.