Can querySelectorAll() select elements by attribute values?
Answers:
Yes,
querySelectorAll()can select elements based on their attribute values using attribute selectors. You can use this method to target elements that have specific attributes, attributes with specific values, or attributes that contain certain values.Here's how you can use attribute selectors with
querySelectorAll():-
Select elements with a specific attribute:
const elementsWithAttr = document.querySelectorAll('[data-custom]');This selects all elements that have the
data-customattribute, regardless of its value. -
Select elements with a specific attribute value:
const elementsWithAttrValue = document.querySelectorAll('[data-custom="example"]');This selects all elements that have the
data-customattribute set to "example". -
Select elements with an attribute value that starts with a specific string:
const elementsStartingWith = document.querySelectorAll('[data-custom^="ex"]');This selects all elements where the
data-customattribute value starts with "ex". -
Select elements with an attribute value that ends with a specific string:
const elementsEndingWith = document.querySelectorAll('[data-custom$="ample"]');This selects all elements where the
data-customattribute value ends with "ample". -
Select elements with an attribute value that contains a specific substring:
const elementsContaining = document.querySelectorAll('[data-custom*="amp"]');This selects all elements where the
data-customattribute value contains "amp".
By using these selectors with
querySelectorAll(), you can easily target elements based on their attribute values in your HTML documents.-