innerHTML, innerText, TextContent 的区别

文章目录

    测试用的 HTML 代码

    <div class="quoteText">
          “Two things are infinite: the universe and human stupidity; and I'm not sure about the universe.”
      <br>  ―
      <span class="authorOrTitle">
        Albert Einstein
      </span>
    </div>
    

    innerHTML

    document.querySelector(".quoteText").innerHTML
    "
          “Two things are infinite: the universe and human stupidity; and I'm not sure about the universe.”
      <br>  ―
      <span class="authorOrTitle">
        Albert Einstein
      </span>
    "
    

    想基于内部 tag 来处理文本时,可以使用 innerHTML.

    textContent

    document.querySelector(".quoteText").textContent
    "
          “Two things are infinite: the universe and human stupidity; and I'm not sure about the universe.”
        ―
      
        Albert Einstein
      
    "
    

    innerText

    document.querySelector(".quoteText").innerText
    "“Two things are infinite: the universe and human stupidity; and I'm not sure about the universe.” 
    ― Albert Einstein"
    

    outerText

    document.querySelector(".quoteText").outerText
    "“Two things are infinite: the universe and human stupidity; and I'm not sure about the universe.” 
    ― Albert Einstein"
    

    outerHTML

    document.querySelector(".quoteText").outerHTML
    "<div class="quoteText">
          “Two things are infinite: the universe and human stupidity; and I'm not sure about the universe.”
      <br>  ―
      <span class="authorOrTitle">
        Albert Einstein
      </span>
    </div>"
    

    innerText 与 textContent 的区别

    从这段测试代码上看,并没有本质上的区别。但是:

    • innerText 会去除 display none 的部分
    • 而 textContent 会全部返回

    关于作者 🌱

    我是来自山东烟台的一名开发者,有感兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊,或者关注我的个人公众号“大象工具”, 查看更多联系方式