Select All Elements With CSS Class Name Starting With, Ending With, Or Containing String
June 23, 2023 by Andreas Wik
As you know, selecting all elements that have a specific class is simple:
.animal {
border: 2px solid black;
}
But there may be times when you want to match all elements that have a class where its name starts with, ends with it, or just simply contains a specific string. Let’s check out how.
To match all elements with a class name that starts with “hotel”, use the ^ symbol:
/* Class name starts with "hotel" */
div[class^="hotel"] {
background: #85c8ea;
}
To match all elements with a class name that contains “safety”, use the * symbol:
/* Class name contains "safety" */
div[class*="safety"] {
background: seagreen;
color: white;
}
To match all elements with a class name that ends with “contact”, use the $ symbol:
/* Class ends with "contact" */
div[class$="contact"] {
background: #eeeeee;
}
Here is a CodePen you can play around with to test it:
See the Pen Untitled by Andreas Wik (@andreaswik) on CodePen.