首页 > 解决方案 > 如果文本相同,如何向元素添加类?

问题描述

我有两个不同div的s:

<div class="first-div">this is the same text</div>
<div class="second-div">this is the same text</div>

是否可以检测两个divs 中的文本是否相同,然后将类添加到第二个div

<div class="second-div newclass">this is the same text</div>

标签: javascripthtmljquery

解决方案


是的,在纯 JS 中是可能的,甚至不需要 jQuery:

const firstDiv = document.querySelector('.first-div');
const secondDiv = document.querySelector('.second-div');
if (firstDiv.textContent === secondDiv.textContent) {
  secondDiv.className += ' new-class';
}

推荐阅读