Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select each class starting with a given string in Pure javaScript [duplicate]

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:

  • select class starting with jquery
  • How to get all elements by class name?
  • Jquery select first letter?

The last one is interesting, but I don't like the idea to loop over each element to check the classes.

like image 645
Mr Robot Avatar asked Mar 13 '19 14:03

Mr Robot


People also ask

What does querySelectorAll() method do?

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.

What does getElementsByClassName() function return?

The getElementsByClassName() method returns a collection of elements with a specified class name(s). The getElementsByClassName() method returns an HTMLCollection.

What is getElementsByClassName in JavaScript?

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.


3 Answers

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>
like image 176
brk Avatar answered Oct 19 '22 18:10

brk


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-"]'.

like image 6
Bhojendra Rauniyar Avatar answered Oct 19 '22 18:10

Bhojendra Rauniyar


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>
like image 1
Maheer Ali Avatar answered Oct 19 '22 18:10

Maheer Ali