Find an element in DOM based on an attribute value

michael picture michael · Apr 22, 2010 · Viewed 395.3k times · Source

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");

Answer

Wojtek Kruszewski picture Wojtek Kruszewski · May 27, 2013

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:

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

$('[data-foo="value"]');