js中innerHTML,innerText,outerHTML textContent 的用法和区别

用法: 

 

<div id="test"> 

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

</div> 

 

在JS中获取值如下: 

 

test.innerHTML: 也就是从对象的起始位置到终止位置的全部内容,包括Html标签。 

 

    上例中的test.innerHTML的值也就是“<span style="color:red">test1</span> test2 ”。 

 

test.innerText: 从起始位置到终止位置的内容, 但它去除Html标签 

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

test.outerHTML: 除了包含innerHTML的全部内容外, 还包含对象标签本身。 

  上例中的text.outerHTML的值也就是<div id="test"><span style="color:red">test1</span> test2</div> 

outerText 设置(包括标签)或获取(不包括标签)对象的文本

      上例中的text.outerText的值也就是test1 test2

textConet:只能用来构造文本节点,如果给传入包含html元素,则会直接按照文本格式吐出来

      上例中的text.outerText的值也就是test1 test2

完整示例: 

 

在js中设置值如下:

    test.innerHTML

             test.innerHTML="<h1 >您好</h1>";

   则最终html会成为:

                  <div id="test"> 

                  <h1>您好</h1>

                  </div> 

        test.innerText

                         test.innerHTML="<h1>您好</h1>";

                    结果:       

                  <div id="test"> 

                  &lt;h1&gt;你好&lt;/h1&gt;

                  </div> 

         

 

        

PS: innerHTML是符合W3C标准的属性,而innerText对Firefox是不支持的,因此,尽可能地去使用innerHTML,而少用innerText,如果要输出不含HTML标签的内容,可以使用innerHTML取得包含HTML标签的内容后,再用正则表达式去除HTML标

 

console.info(document.getElementById('mydiv').innerHTML.replace(/<.+?>/gim,'')); 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值