I would like to select any element owning a class starting by a given string, here is an example where the classes start with fi-
<i class="fi-xmsl-user"></i>
<i class="fi-stsl-map"></i>
I would like to do this in pure JavaScript (no jQuery).
I already read the following questions:
The last one is interesting, but I don't like the idea to loop over each element to check the classes.
querySelectorAll() The Document method querySelectorAll() returns a static (not live) NodeList representing a list of the document's elements that match the specified group of selectors.
The getElementsByClassName() method returns a collection of elements with a specified class name(s). The getElementsByClassName() method returns an HTMLCollection.
The getElementsByClassName method of Document interface returns an array-like object of all child elements which have all of the given class name(s). When called on the document object, the complete document is searched, including the root node.
Use document.querySelectorAll
and wild card selector. Here class^
mean that this query selector will select any element who have a class starting with fi
let k = document.querySelectorAll('[class^="fi"]');
console.log(k)
<i class="fi-xmsl-user"></i>
<i class="fi-stsl-map"></i>
You can fine tune it to select only i
tag by passing the tag
name
let k = document.querySelectorAll('i[class^="fi"]');
console.log(k.length)
<i class="fi-xmsl-user"></i>
<i class="fi-stsl-map"></i>
<div class="fi-stsl-map"></div>
You can use querySelectorAll and specify the selector how you do in jQuery like:
document.querySelectorAll('[class^="fi"]')
And if you don't want to match other classes that starts with fi
like fish
but just match them with dash then you know the deal exactly like jQuery: '[class^="fi-"]'
.
You can use Attribute Selectors
and querySelectorAll()
[attr^=value]
Represents elements with an attribute name of attr whose value is prefixed (preceded) by value
let i = document.querySelectorAll('[class^=fi]')
console.log([...i])
<i class="fi-xmsl-user"></i>
<i class="fi-stsl-map"></i>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With