531

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

11 Answers 11

839

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"]'); 
Sign up to request clarification or add additional context in comments.

7 Comments

in order to concretize the "modern" definition: caniuse.com/#search=querySelectorAll
The selector should be: '[data-foo="value"]'
Any notes about perfomance? Is this faster then iterating over all nodes?
Note that the "jQuery" example might not be jQuery. It could be Chrome or Firefox implementation of $. Read more about this here: stackoverflow.com/questions/22244823/…
What is "data-foo" ...and where is 'myAttribute' gone in this example?
|
237

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.

1 Comment

I keep getting an empty array! I'm trying to grab an SVG by it's d attribute, and am trying $("[d=path]"); where 'path' is a variable containing the specific d-attribute I need. Has anyone tried doing this with svg paths?
125

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

1 Comment

I had to remove inner quote marks like this document.querySelectorAll("selector[myAttribute=aValue]");
28

Use query selectors. Examples:

document.querySelectorAll(' input[name], [id|=view], [class~=button] ') 

input[name] Inputs elements with name property-attribute.

[id|=view] Elements with id attribute that start with view-.

[class~=button] Elements with the button class.

1 Comment

hi is there a good ref. explaining these and more
17
FindByAttributeValue("Attribute-Name", "Attribute-Value"); 

p.s. if you know exact element-type, you add 3rd parameter (i.e.div, a, p ...etc...):

FindByAttributeValue("Attribute-Name", "Attribute-Value", "div"); 

but at first, define this function:

function FindByAttributeValue(attribute, value, element_type) { element_type = element_type || "*"; var All = document.getElementsByTagName(element_type); for (var i = 0; i < All.length; i++) { if (All[i].getAttribute(attribute) == value) { return All[i]; } } } 

p.s. updated per comments recommendations.

5 Comments

Why ?! You're looping all your DOM by doing this
This seems great - if you only have 5 elements on the page.
document.querySelectorAll('[data-foo="value"]'); as proposed by @Wojtek Kruszewski on accepted awnser.
querySelector and querySelectorAll give you static nodes, the snippet by @T.Todua returns live nodes. That might be a reason to do it this way.
@ErikOosterwaal incorrect, querySelectorAll returns a static collection of nodes. The nodes inside are still live and would reflect any changes done to them, it's just that the collection does not update as the document updates. As opposed to, for example, document.getElementsByClassName("foo") which will return a collection that does live update. The nodes inside are otherwise the same as what you'd get from document.querySelectorAll(). To that effect, the snippet in this answer does not return a live collection but a single node.
14

Here's how you can select using querySelector:

document.querySelector("tagName[attributeName='attributeValue']") 

Comments

11

very simple, try this

<h1>The Document Object</h1> <h2>The querySelector() Method</h2> <h3>Add a background color to the first p element:</h3> <p>This is a p element.</p> <p data-vid="1">This is a p element.</p> <p data-vid="2">This is a p element.</p> <p data-vid="3">This is a p element.</p> <script> document.querySelector("p[data-vid='1']").style.backgroundColor = "red"; document.querySelector("p[data-vid='2']").style.backgroundColor = "pink"; document.querySelector("p[data-vid='3']").style.backgroundColor = "blue"; </script>

Comments

10

Amendment for Daniel De León's Answer
It's possible to search with
^= - filters Elements where id (or any other attr) starts with view keyword

document.querySelectorAll("[id^='view']") 

Comments

8

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

Comments

8

you could use getAttribute:

 var p = document.getElementById("p"); var alignP = p.getAttribute("align"); 

https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute

1 Comment

He want to select the p element without using id or every p on the DOM (and test attributes)
0
function optCount(tagId, tagName, attr, attrval) { inputs = document.getElementById(tagId).getElementsByTagName(tagName); if (inputs) { var reqInputs = []; inputsCount = inputs.length; for (i = 0; i < inputsCount; i++) { atts = inputs[i].attributes; var attsCount = atts.length; for (j = 0; j < attsCount; j++) { if (atts[j].nodeName == attr && atts[j].nodeValue == attrval) { reqInputs.push(atts[j].nodeName); } } } } else { alert("no such specified tags present"); } return reqInputs.length; }//optcount function closed 

This is a function which is is used tu to select a particular tag with specific attribute value. The parameters to be passed are are the tag ID, then the tag name - inside that tag ID, and the attribute and fourth the attribute value. This function will return the number of elements found with the specified attribute and its value. You can modify it according to you.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.