How to Use Attribute Selectors with querySelector in JavaScript
The querySelector and querySelectorAll methods are incredibly powerful tools for selecting DOM elements, and their power is magnified when you use CSS attribute selectors. These selectors allow you to find elements based on the presence or value of any HTML attribute, such as title, href, data-*, or even class.
This guide will teach you how to use the most common attribute selectors to find elements whose attributes contain, start with, or end with a specific string.
The Core Method: querySelector with Attribute Selectors
The querySelector and querySelectorAll methods both accept a CSS selector string. The syntax for an attribute selector is to use square brackets [...].
element.querySelector('[attribute="value"]')
The Main Attribute Selectors
While a simple [attribute="value"] checks for an exact match, the real power comes from the "fuzzy match" selectors:
| Selector | Meaning | Example |
|---|---|---|
[attr*="val"] | Attribute contains the value val. | [class*="icon-"] |
[attr^="val"] | Attribute starts with the value val. | [href^="https://"] |
[attr$="val"] | Attribute ends with the value val. | [src$=".png"] |
Use Case 1: Attribute Contains a Substring (*=)
This is the most common use case. It allows you to find an element where a substring appears anywhere within the attribute's value.
For example, you need to find all elements that have a class attribute containing the substring "box".
<div class="box-primary">Box 1</div>
<div class="box-secondary">Box 2</div>
<div class="container">Container 3</div>
The solution is to use the *= selector to find any element whose class attribute contains "box".
// Select all elements with a class containing "box"
const boxes = document.querySelectorAll('[class*="box"]');
console.log(boxes); // Output: NodeList(2) [div.box-primary, div.box-secondary]
You can make the selector more specific by adding a tag name:
// Select only <div> elements with a class containing "box"
const divBoxes = document.querySelectorAll('div[class*="box"]');
Use Case 2: Attribute Starts With a Substring (^=)
This selector is perfect for finding elements that share a common prefix, such as all links that point to a secure site.
For example, you want to select all <a> tags that have an href attribute starting with https://.
<a href="https://example.com">Secure Link</a>
<a href="http://anothersite.com">Insecure Link</a>
<a href="/local-page">Local Link</a>
The solution is to use the ^= selector.
// Select all anchor tags whose href starts with "https://"
const secureLinks = document.querySelectorAll('a[href^="https://"]');
console.log(secureLinks.length); // Output: 1
Use Case 3: Attribute Ends With a Substring ($=)
This selector is very useful for finding files of a specific type, like all images that are PNGs.
For example, you need to find all <img> elements whose src attribute ends with .png.
<img src="images/logo.png" alt="Logo">
<img src="images/banner.jpg" alt="Banner">
The solution is to use the $= selector.
// Select all image elements whose src ends with ".png"
const pngImages = document.querySelectorAll('img[src$=".png"]');
pngImages.forEach(img => {
img.style.border = '2px solid blue'; // Apply a style to the matched images
});
querySelector vs. querySelectorAll
It's important to choose the right method for your needs.
querySelector(): Returns the first element that matches the selector. If no match is found, it returnsnull. Use this when you only expect one result or only care about the first one.const firstBox = document.querySelector('[class*="box"]'); // Returns the div.box-primary elementquerySelectorAll(): Returns aNodeListcontaining all elements that match the selector. If no matches are found, it returns an emptyNodeList. Use this when you expect multiple results.const allBoxes = document.querySelectorAll('[class*="box"]'); // Returns a NodeList with 2 elements
Conclusion
CSS attribute selectors dramatically increase the power and flexibility of querySelector and querySelectorAll.
- Use
[attr*="value"]to find elements where an attribute contains a substring. - Use
[attr^="value"]to find elements where an attribute starts with a substring. - Use
[attr$="value"]to find elements where an attribute ends with a substring.
By mastering these simple but powerful selectors, you can write more concise, readable, and efficient DOM selection code without needing to manually inspect element properties in a loop.