QuerySelector attribute starts with Examples using JavaScript

avatar

Borislav Hadzhiev

Mon Dec 27 20211 min read

banner

Photo by Radu Spătaru

QuerySelector attribute starts with Examples #

To get the DOM elements, which have an attribute starting with a specific value, pass the following selector to the querySelectorAll method - '[title^="box"]'. The selector matches all of the DOM elements that have a title attribute that starts with the string box.

Here is the HTML for the examples in this article.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div title="box1">Box 1</div> <div title="box2">Box 2</div> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
const boxes = document.querySelectorAll('[title^="box"]'); console.log(boxes); // 👉️ [div, div] const box = document.querySelector('[title^="box"]'); console.log(box); // 👉️ div

We used the document.querySelectorAll method to select all of the DOM elements that have a title attribute that starts with the string box.

You might be familiar with the care ^, which has the same meaning when used in regular expressions.

The second example uses the document.querySelector method, which returns the first element within the document that matches the provided selector.

In short, if you're looking for a single element that matches the provided selector, use querySelector(), and if you're looking for a collection of elements, use querySelectorAll().

You can also make the query more specific by only looking for div elements that have an attribute value that starts with a specific string.

index.js
const boxes = document.querySelectorAll('div[title^="box"]'); console.log(boxes); // 👉️ [div, div] const box = document.querySelector('div[title^="box"]'); console.log(box); // 👉️ div

The selectors we passed to the querySelectorAll and querySelector methods would not not match any span or p elements even if they have a title attribute that starts with the string box.

Use the search field on my Home Page to filter through my more than 1,000 articles.