javascript - 如果文本相同,如何向元素添加类?
问题描述
我有两个不同div
的s:
<div class="first-div">this is the same text</div>
<div class="second-div">this is the same text</div>
是否可以检测两个div
s 中的文本是否相同,然后将类添加到第二个div
?
<div class="second-div newclass">this is the same text</div>
解决方案
是的,在纯 JS 中是可能的,甚至不需要 jQuery:
const firstDiv = document.querySelector('.first-div');
const secondDiv = document.querySelector('.second-div');
if (firstDiv.textContent === secondDiv.textContent) {
secondDiv.className += ' new-class';
}
推荐阅读
- google-chrome-extension - 我如何在没有 devtools-network 的情况下获得 m3u8 地址?
- android - 当滚动到达第一个位置顶部时,Recycleview 加载更多数据
- html - 如何使用不同的 IONIC CSS 边距和填充
- python - 遇到 ParseError: not well-formed (invalid token): 将 XML 转换为 DataFrame 时出现问题
- java - 当调用多个静态方法时,使用 Mockito 验证静态方法调用
- azure - 从 Azure FHIR 服务请求 FHIR 资源时出现身份验证错误
- c# - 如何在解决方案中获取特定文件夹的路径
- python - Have gradient colors and increasing marker sizes for two columns of a dataframe so that I can see which datapoints are connected to each other?
- python - 无法弄清楚带有分箱 lambda 函数的循环的作用
- opencv - 如何在 GoCV(opencv 4)中裁剪 cuda.GpuMat?