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 $('[class^="fruit-"]').doSomething(...)
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> $('[class^="fruit-"]').doSomething(...) // won't match <div class="basket-item fruit-apple">🍏</div> $('[class^="fruit-"]').doSomething(...)
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> $('[class*="vegetable-"]').doSomething(...) // will also match <div class="basket-item vegetable-potato">🥔</div> $('[class*="vegetable-"]').doSomething(...)
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!