innertext与innerhtml

Posted hq金水

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了innertext与innerhtml相关的知识,希望对你有一定的参考价值。

<div id="test"> 
<span style="color:red">test1</span> test2

</div>
<a
href="javascript:alert(test.innerhtml)">innerHTML内容</a>
<a
href="javascript:alert(test.innerText)">inerHTML内容</a>

共同点:innerHTML和innerText都会把元素内内容替换掉。
不同点:
1,innerHTML:
  也就是从对象的起始位置到终止位置的全部内容,包括Html标签。

  上例中的test.innerHTML的值也就是“<span style="color:red">test1</span>
test2 ”。
2,innerText:
  从起始位置到终止位置的内容, 但它去除Html标签

  上例中的text.innerTest的值也就是“test1 test2”, 其中span标签去除了。

值得注意的是,innerHTML是符合W3C标准的属性,而innerText只适用于IE浏览器,因此,尽可能地去使用innerHTML,而少用innerText,如果要输出不含HTML标签的内容,可以使用innerHTML取得包含HTML标签的内容后,再用正则表达式去除HTML标签。

以上是关于innertext与innerhtml的主要内容,如果未能解决你的问题,请参考以下文章

innertext与innerhtml

JavaScript中innerHTML与innerText,createTextNode的区别

innerHTML与innerText的异同

如何让“.innerText”忽略不可见元素的不可见子元素?

JavaScript笔记--- DOM(初步)(获取文本框value;innerHTML与innerText;正则表达式;去除字符串的前后空白trim;表单验证)

处理innerText的兼容性问题