Home >Web Front-end >JS Tutorial >How to Efficiently Find DOM Elements by Attribute Value?
How to Find an Element in DOM Based on an Attribute Value
Searching for an element in the Document Object Model (DOM) based on an attribute value is a common task in web development. DOM APIs provide robust mechanisms to perform this operation.
In modern browsers, querySelectorAll is a native method that allows you to retrieve elements that match a given CSS selector. For instance, to find elements with a specific data-foo attribute set to "value," you can use the following selector:
document.querySelectorAll('[data-foo="value"]');
This method is supported by all major modern browsers, as detailed on MDN: https://developer.mozilla.org/en-US/docs/Web/API/Document.querySelectorAll and https://caniuse.com/queryselector.
For obsolete browsers such as IE9 and earlier, you can use the jQuery library to achieve the same functionality:
$('[data-foo="value"]');
The above is the detailed content of How to Efficiently Find DOM Elements by Attribute Value?. For more information, please follow other related articles on the PHP Chinese website!