如何检查元素classlist是否部分包含字符串或单词?
我有这个代码:
const all = document.querySelectorAll('div');
let variable = 'fruits';
all.forEach((item) => {
if(item.classList.contains(variable)) {
item.style.backgroundColor = 'red';
}
});
<div class="fruits">
Fruits
</div>
<div class="fruits-green">
Green fruits
</div>
我想知道是否有classList.contains用字符串/单词部分使用?
显然,我要实现的目标也是要使水果绿色造型,因为它包含水果 green,
我知道有CSS选择器为此,但是鉴于我的水果变量会随其他JS而变化。功能,我也希望这也是香草JS。
任何建议都非常感谢。 谢谢!
I've got this code:
const all = document.querySelectorAll('div');
let variable = 'fruits';
all.forEach((item) => {
if(item.classList.contains(variable)) {
item.style.backgroundColor = 'red';
}
});
<div class="fruits">
Fruits
</div>
<div class="fruits-green">
Green fruits
</div>
and I was wondering if theres to use classList.contains with a string/word partially?
Obviously what I'm trying to achieve is to get fruits-green styled too, since it contains fruits-green
I know there are CSS selectors for that, but given that my fruits variable will change with other JS functions, I'd like this to be vanilla JS too.
Any advice is much appreciated.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我能够使用
再次感谢@david
I was able to make it work using
Thanks again @David
classList
属性是domtokenlist
,它是字符串,但具有模拟数组方法的方法和属性。ash all
)。我们将使用.flatmap()
,因为我们正在处理可能具有或可能没有多个匹配的多个标签。.value
classList
的属性,该属性返回标签的每个类的空间划界字符串。.includes()
进行比较,我们将.filter()
每个标签的每个类The
classList
property is aDOMTokenList
which is a string but has methods and properties simular to Array methods.all
). We'll use.flatMap()
because we are dealing with multiple tags that may or may not have multiple matches..value
property ofclassList
which returns a space delimited string of each of the tag's classes..filter()
each class of each tag by comparing with.includes()