javascript - 将类添加到包含 innerHTML 字符串的 div
问题描述
我正在尝试在div
包含字符串的页面上为每个添加一个 CSS 类Subject:
我试过了
var elList = document.querySelectorAll("div");
elList.forEach(function(el) {
if (el.innerHTML.indexOf("Subject") !== -1) {
console.log(el);
el.setAttribute('class', "newClass");
}
});
但它没有返回任何节点。并且
var headings = document.evaluate("//*[contains(normalize-space(text()), 'Subject:')]", document, null, XPathResult.ANY_TYPE, null );
while(thisHeading = headings.iterateNext()){
thisHeading.setAttribute('class', "newClass");
console.log(thisHeading);
}
它返回的XPathResult
似乎没有任何节点作为对象的一部分。
这就是 HTML 的样子,尽管它深深地嵌套在文档正文中。
<div class="note-stream-header">Subject: Please Reply to This</div>
如何选择包含字符串的所有节点并使用 JS 向它们添加类?
解决方案
您的方法很好,但是由于您对元素的内容感兴趣,请使用.textContent
而不是innerHTML
.
请参阅内联的其他评论。
// .forEach is not supported in all browsers on node lists
// Convert them to arrays first to be safe:
var elList = Array.prototype.slice.call(
document.querySelectorAll("div"));
elList.forEach(function(el) {
// Use .textContent when you aren't interested in HTML
if (el.textContent.indexOf("Subject") > -1) {
console.log(el);
el.classList.add("newClass"); // Use the .classList API (easier)
}
});
.newClass { background-color:#ff0; }
<div>The subject of this discussion is JavaScript</div>
<div>The topic of this discussion is JavaScript</div>
<div>The queen's royal subjects weren't amused.</div>
<div>Subject: textContent DOM property</div>
推荐阅读
- laravel - 使用 gmail smtp-relay(数据库队列驱动程序)的 laravel swift-mailer 异常“预期响应代码 250,但得到一个空响应”
- android - 在创建活动 Android 之前启动协程
- javascript - 未调用socket.io“连接”事件
- postgresql - 创建 hstore 索引时出现 Liquibase Postgres 错误
- swiftui - 使用 NavigationLink 时不重新加载选项卡项的 SwiftUI 问题
- javascript - 在 html、JS 和 Node 之间向 MongoDB 发送数据的正确方法
- python - Python 获取所有股票行情
- bash - Bash:同一行上多个命令的输出
- python - numpy.where , numpy.take 和多维数组上的索引
- angular - Angular 2+ (v11) 自动将 URL 中的片段哈希 (#) 编码为 %23