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");
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Update: In the past few years the landscape has changed drastically. You can now reliably use
querySelectorandquerySelectorAll, 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:
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):
You can also do
start-with,ends-with,contains, etc…there are several options for the attribute selector.