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

☆樱花仙子☆ 提交于 2021-01-27 17:56:10

问题


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.


回答1:


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>



回答2:


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




回答3:


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>



回答4:


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>


来源:https://stackoverflow.com/questions/55144239/select-each-class-starting-with-a-given-string-in-pure-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!