475

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");
Nakilon
  • 34,866
  • 14
  • 107
  • 142
michael
  • 106,540
  • 116
  • 246
  • 346

11 Answers11

761

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"]');
Wojtek Kruszewski
  • 13,940
  • 6
  • 38
  • 38
  • 2
    in order to concretize the "modern" definition: http://caniuse.com/#search=querySelectorAll – serhio Mar 31 '15 at 16:23
  • It seems that value can not be a number or `SyntaxError: An invalid or illegal string was specified` – jeum Apr 21 '15 at 15:16
  • 5
    The selector should be: `'[data-foo="value"]'` – Yotam Omer Feb 25 '16 at 01:20
  • 1
    Any notes about perfomance? Is this faster then iterating over all nodes? – Stepan Yakovenko Jul 29 '16 at 09:07
  • 2
    Note that the "jQuery" example might not be jQuery. It could be Chrome or Firefox implementation of `$`. Read more about this here: https://stackoverflow.com/questions/22244823/what-is-the-dollar-sign-in-javascript-if-not-jquery – Esdras Lopez Apr 18 '18 at 09:15
  • 4
    What is "data-foo" ...and where is 'myAttribute' gone in this example? – oo_dev Dec 17 '19 at 08:13
  • 1
    This is the correct answer as 99.99% of browsers support this without JQuery. It's a shame stackoverflow doesn't let us depreciate old answers or notify people who answered them when they are out of date :( – Nick Steele Apr 26 '21 at 00:00
  • This worked like charm! – Rohit Parte Nov 24 '21 at 17:09
229

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.

brasofilo
  • 25,496
  • 15
  • 91
  • 179
Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
  • 1
    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? – tx291 Nov 28 '16 at 15:45
119

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

albert
  • 8,112
  • 3
  • 47
  • 63
Naveen Pantra
  • 1,236
  • 1
  • 8
  • 7
18

Use query selectors. Examples:

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

input[name] Inputs elements with name property.

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

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

isherwood
  • 58,414
  • 16
  • 114
  • 157
Daniel De León
  • 13,196
  • 5
  • 87
  • 72
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.

T.Todua
  • 53,146
  • 19
  • 236
  • 237
  • 9
    Why ?! You're looping all your DOM by doing this – Arthur Apr 13 '17 at 14:28
  • 4
    This seems great - if you only have 5 elements on the page. – sheriffderek Sep 01 '17 at 16:31
  • 3
    `document.querySelectorAll('[data-foo="value"]');` as proposed by @Wojtek Kruszewski on accepted awnser. – Arthur Nov 18 '17 at 19:58
  • 1
    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. – Erik Oosterwaal Aug 23 '22 at 20:31
  • @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. – VLAZ Aug 29 '23 at 13:05
13

Here's how you can select using querySelector:

document.querySelector("tagName[attributeName='attributeValue']")
Siddharth
  • 543
  • 6
  • 15
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']");
boubkhaled
  • 379
  • 5
  • 6
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

Deke
  • 4,451
  • 4
  • 44
  • 65
  • 3
    He want to select the `p` element without using `id` or every `p` on the DOM (and test attributes) – Arthur Apr 13 '17 at 14:29
8

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']")
GDeriyenko
  • 96
  • 1
  • 7
7

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>
isherwood
  • 58,414
  • 16
  • 114
  • 157
VnDevil
  • 1,321
  • 15
  • 13
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.

VLAZ
  • 26,331
  • 9
  • 49
  • 67