首页 > 解决方案 > 将类添加到包含 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 向它们添加类?

标签: javascriptcssxpathinnerhtml

解决方案


您的方法很好,但是由于您对元素的内容感兴趣,请使用.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>


推荐阅读