4

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.

Mr Robot
  • 775
  • 7
  • 15
  • You're looking for a *"wildcard selector"*. Possible duplicate of [querySelector, wildcard element match?](https://stackoverflow.com/questions/8714090/queryselector-wildcard-element-match) – Tyler Roper Mar 13 '19 at 14:28
  • Yeah .. wildcard was the right keyword. Thank you. – Mr Robot Mar 13 '19 at 14:48

4 Answers4

9

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>
brk
  • 43,022
  • 4
  • 37
  • 61
6

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

marc_s
  • 675,133
  • 158
  • 1,253
  • 1,388
Bhojendra Rauniyar
  • 73,156
  • 29
  • 131
  • 187
  • I'm having same issues, It works without the hyphen '-' but I need to add the hyphen to make it specific. Once i add the hyphen, it stops working. Please help – Pelumi Dec 13 '19 at 11:58
  • @Pelumi What's your class exactly and how you use hyphen in query selector? – Bhojendra Rauniyar Dec 13 '19 at 12:42
1

You can use .querySelectorAll with the ^ into the selector like

document.querySelectorAll('[class^="fi-"]')

Live demo

console.log(document.querySelectorAll('[class^="fi-"]'))
<div class="fi-one"></div>
<div class="fi-two"></div>
R3tep
  • 11,061
  • 9
  • 38
  • 69
  • I'm having same issues, It works without the hyphen '-' but I need to add the hyphen to make it specific. Once i add the hyphen, it stops working. Please help – Pelumi Dec 13 '19 at 11:59
  • @Pelumi The live demo is working, so I don't understand why it's not working for you. Check your implementation – R3tep Dec 13 '19 at 12:16
1

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>
Maheer Ali
  • 32,967
  • 5
  • 31
  • 51