有没有一种方法可以将类添加到后面跟有字符的元素中



我有一些HTML,看起来像这样:

<p>
<span class="word">keyword</span>
()
<span class="word">another keyword</span>
</p>

我如何使用JavaScript(无jQuery(将类添加到类为"的任何元素中;单词";其具有";("字符直接在其后面?HTML应该是这样的:

<p>
<span class="word parenthesis">keyword</span>
()
<span class="word">another keyword</span>
</p>

使用@Barmar的评论,我成功地写下了这个:

document.querySelectorAll('.word').forEach((el) => {
if (el.nextSibling.data.trim().charAt(0) === '(') {
el.classList.add('parenthesis');
}
});

let classList = document.querySelectorAll('.word');
for (let i = 0; i < classList.length; i++) {
classList[i].classList.add("anotherClass");
//classList[i].classList.remove("word");
}
.anotherClass {
font-weight: bold;
}
<p>
<span class="word">keyword</span>
<span class="">-No class-</span>
<span class="word">keyword</span>
<span class="word">another keyword</span>
<span class="word">keyword</span>
<span class="">-No class-</span>
<span class="word">keyword</span>
<span class="word">another keyword</span>
</p>

最新更新