innerHTML、innerText、textContent、outerHTML和value,傻傻分不清楚?

原文地点:
https://www.xksblog.top/innerHTML-innerText-textContent-outerHTML-value.html

innerHTML、innerText、textContent、outerHTML和value,傻傻分不清晰?什么时刻该用哪一个?虽然我们经常运用的老是innerHTML,但在一些特别情况下,准确的挑选可以事半功倍,所以是时刻对这几个小家伙细致分分清晰了。

一个栗子

空话不多说,先来看个例子:

<h1>innerHTML、innerText、textContent、outerHTML和value的辨别</h1>
<p id="content-wrapper">你是谁?
  <span>这是一个内嵌span测试</span>
</p>
<input id="name-input" type="text" placeholder="输入你的名字" value="xk">
<button id="send-btn">发送</button>
<script>
  let contentWrapper = document.getElementById("content-wrapper")
  let nameInput = document.getElementById("name-input")
  let sendBtn = document.getElementById("send-btn")

  console.log("文本p的innerHTML是:" + contentWrapper.innerHTML)
  console.log("文本p的innerText是:" + contentWrapper.innerText)
  console.log("文本p的textContent是:" + contentWrapper.textContent)
  console.log("文本p的outerHTML是:" + contentWrapper.outerHTML)
  console.log("文本p的value是:" + contentWrapper.value)

  console.log("input的innerHTML是:" + nameInput.innerHTML)
  console.log("input的innerText是:" + nameInput.innerText)
  console.log("input的textContent是:" + nameInput.textContent)
  console.log("input的outerHTML是:" + nameInput.outerHTML)
  console.log("input的value是:" + nameInput.value)

  console.log("按钮button的innerHTML是:" + sendBtn.innerHTML)
  console.log("按钮button的innerText是:" + sendBtn.innerText)
  console.log("按钮button的textContent是:" + sendBtn.textContent)
  console.log("按钮button的outerHTML是:" + sendBtn.outerHTML)
  console.log("按钮button的value是:" + sendBtn.value)
</script>

效果如图:
《innerHTML、innerText、textContent、outerHTML和value,傻傻分不清楚?》

看完了实在照样一脸懵逼状。。有的值一样,有的甚至连值都不见了,什么鬼?好了总结一下:

innerHTML

innerHTML用来设置或猎取成对标签之间的HTML内容,包含个中内嵌的子元素标签。

  • innerHTML会显现内嵌的标签,所以文本p的innerHTML会有内嵌的span
  • 运用innerHTML的元素必需是标签对的情势,所以input的innerHTML值为空
  • innerHTML保留了花样信息,所以文本p的innerHTML内容会有换行

innerText

innerText也用来设置或猎取成对标签之间的HTML内容,但它只关注文本信息,会省略内嵌的标署名。

  • innerHTML会省略内嵌的标署名,所以文本p的innerHTML只显现了span的内容,并没有显现span的标署名
  • innerText也必需是标签对的情势
  • innerText删除了花样信息,一切文本均在一行,所以文本p的innerText内容都在一行。

textContent

textContent也用来设置或猎取成对标签之间的HTML内容,而且只关注文本信息。

  • 这家伙和innerText一样一样的,但它保留了花样信息。

outerHTML

outerHTML设置或猎取元素及其内容的HTML情势。

  • 这个是最好辨别的,直接看例子,它会把DOM元素自身的标签+内容+花样悉数显现出来。

value

value是表单元素特有的属性,一般input用的比较多,就是个中输入的值,也很好辨别。

innerHTML、innerText和textContent的再次较劲

我们还要再把这三个难兄难弟挑出来,从浏览器兼容的角度来辨别一下:

innerHTML是相符W3C规范的属性,而innerText适用于IE浏览器,textContent适用于火狐浏览器。

这也就是为何我们总能看到innerHTML,总对它偏幸有加,毕竟是W3C的亲儿子嘛。

只不过到了本日,其他的浏览器也都完成了innerText和textContent,但要注重的是:

  • IE6-8只部份支撑了innerHTML,在IE下,跟table有关的元素的innerHTML是只读的,我们没法转变其值;从IE9最先,周全支撑了innerHTML。
  • IE9之前,是不支撑textContent的。
  • innerText是IE的亲儿子,宁神用吧。
    原文作者:stay1100
    原文地址: https://segmentfault.com/a/1190000016200638
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞