javascript get by - Find an element in DOM based on an attribute value





3 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:

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

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

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



We can use attribute selector in DOM by using document.querySelector() and document.querySelectorAll() methods.

for yours:

document.querySelector("<selector>[myAttribute = \'aValue\']");

and by using querySlectorAll():

document.querySelectorAll("<selector>[myAttribute] = \'aValue\'");

In querySelector() and querySelectorAll() methods we can select objects as we select in "CSS".

\' in here represent escape character and it finally represent selector[myAttrubute = aValue] just as in "CSS".

More about "CSS" attribute selectors in https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors




Here is an example , How to search images in a document by src attribute :

document.querySelectorAll("img[src='https://pbs.twimg.com/profile_images/........jpg']");



Related