innerHTML, innerText, TextContent 的区别

发布时间: 2018-12-15 22:07:01 作者: 大象笔记

测试用的 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 的区别

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

我是一名山东烟台的开发者,联系作者