我正在尝试向包含字符串 Subject:
的页面上的每个 div
添加一个 CSS 类
我试过了
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>
关于javascript - 将类添加到包含 innerHTML 字符串的 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53841417/