Get element stating with class in js

How to get an Element Starting with Class Name: the * and ^ JavaScript Selectors

You certainly know * and ^ as selectors in different programming languages. But you may have found some surprising (or frustrating) results while using them as JavaScript or jQuery selectors.

Let’s say you want to access elements starting with a certain class name, for example, “fruit-“ in the following code:

<div class="basket-item fruit-apple">🍏</div>

First, the syntax

Your first reflex may be to try something like that:

// Incorrect syntax
$('.^fruit-').doSomething(...) // Nope, that won't work...

The correct syntax is:

// Correct syntax

Then, the selectors: ^ vs *

Using the ^ selector is correct, but its behavior is a bit too literal: it will get the very first element starting with the class name, or more specifically, the class starting with the selected name.

// will match <div class="fruit-strawberry basket-item">🍓</div>

// won't match <div class="basket-item fruit-apple">🍏</div>

To match a class name starting with “fruit-“ anywhere in the class string, you will need to use the * selector:

// will match <div class="vegetable-carrot basket-item">🥕</div>

// will also match <div class="basket-item vegetable-potato">🥔</div>

Here is a full example to play with on CodePen:

I hope you found it useful. Feel free to buy me a coffee (or tea) to support the blog 🙂
Happy Coding!

Leave a Comment

You want to leave a comment? Sweet! Please do so, but keep in mind that all comments are moderated and rel="nofollow" is in use. So no fake comment or advertisement will be approved. And don't worry, your email address won't be published. Thanks!

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>