Home >Web Front-end >JS Tutorial >How Can I Find DOM Elements Using Attribute Values?

How Can I Find DOM Elements Using Attribute Values?

Barbara Streisand
Barbara StreisandOriginal
2024-12-04 15:01:14980browse

How Can I Find DOM Elements Using Attribute Values?

Finding DOM Elements by Attribute Values

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

Modern browsers support native querySelectorAll, allowing you to do:

document.querySelectorAll('[data-foo="value"]');

Check this documentation for more details: https://developer.mozilla.org/en-US/docs/Web/API/Document.querySelectorAll

For browser compatibility information:

  • http://quirksmode.org/dom/core/#t14
  • http://caniuse.com/queryselector

For obsolete browsers (IE9 and older), you can use jQuery:

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

The above is the detailed content of How Can I Find DOM Elements Using Attribute Values?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn