代码之家  ›  专栏  ›  技术社区  ›  Matthew

向包含innerHTML字符串的div添加类

  •  0
  • Matthew  · 技术社区  · 7 年前

    div 在包含字符串的页面上 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>
    

    1 回复  |  直到 7 年前
        1
  •  1
  •   Scott Marcus    7 年前

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