Mon Dec 27 2021·1 min read
Photo by Hanny Naibaho
To get the DOM elements by partially matching their class names, pass the
following selector to the
querySelectorAll method -
selector matches all of the DOM elements that have a class name that contains
Here is the HTML for the examples in this article.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div class="box1">Box 1</div> <div class="box2">Box 2</div> <script src="index.js"></script> </body> </html>
const boxes = document.querySelectorAll('[class*="box"]'); console.log(boxes); // 👉️ [div.box1, div.box2] const box = document.querySelector('[class*="box"]'); console.log(box); // 👉️ div.box1
We used the
method to select all of the DOM elements that have a class that contains the
The string can be located anywhere in the class name to match the query.
The second example uses the document.querySelector method, which returns the first element within the document that matches the provided selector.
querySelector(), and if you're looking for a collection of elements, use
You can also make the query more specific by only looking for
that have a class that contains the string
const boxes = document.querySelectorAll('div[class*="box"]'); console.log(boxes); // 👉️ [div.box1, div.box2]
The selector we passed to the
querySelectorAll method would not not match any
p elements even if they have a class that contains the string
I'll send you 1 email a week with links to all of the articles I've written that week