innerHTML與innerText區別

來源:互聯網
上載者:User

標籤:body   包括   sdn   clip   開啟   簡單   assets   family   innertext   

document 對象中有innerHTML和innerText 兩個屬性, 這兩個屬性都是擷取document對象的常值內容的,這兩個屬性間有哪些區別呢?通過幾個例子來看一下。

樣本1[html] view plain copy
  1. <html>  
  2.     <head><title>innerHTML</title></head>  
  3.     <body>  
  4.         <p id="p1">hello world </p>  
  5.         <script>  
  6.             var content = document.getElementById("p1");  
  7.             alert(content.innerHTML);  
  8.             alert(content.innerText)  
  9.         </script>  
  10.     </body>  
  11. </html>  


通過IE瀏覽器開啟,彈出內容為 "hello world" 和 "hello world"

通過 Firefox 瀏覽器開啟,彈出內容為 "hello world" 和 "undefined"

通過 chrome 瀏覽器開啟,彈出內容為 "hello world" 和 "hello world"


樣本2[html] view plain copy
  1. <html>  
  2.     <head><title>innerHTML</title></head>  
  3.     <body>  
  4.         <div id="d1"><p id="p1">hello world </p></div>  
  5.         <script>  
  6.             var content = document.getElementById("d1");  
  7.             alert(content.innerHTML);  
  8.             alert(content.innerText)  
  9.         </script>  
  10.     </body>  
  11. </html>  


通過IE瀏覽器開啟,彈出內容為 和 通過 Firefox 瀏覽器開啟,彈出內容為 和 通過 chrome 瀏覽器開啟,彈出內容為 和

通過上面兩個樣本,可以看出:

innerHTML指的是從對象的起始位置到終止位置的全部內容,包括Html標籤。
innerText   指的是從起始位置到終止位置的內容,但它去除Html標籤。
同時,innerHTML 是所有瀏覽器都支援的,innerText 是IE瀏覽器和chrome 瀏覽器支援的,Firefox瀏覽器不支援。其實,innerHTML 是W3C 組織規定的屬性;而innerText 屬性是IE瀏覽器自己的屬性,不過後來的瀏覽器部分實現這個屬性罷了。

outerHTML

說到innerHTML,順便說一下跟innerHTML相對的outerHTML 屬性。

繼續看上面的代碼,將alert(content.innerText) 修改為 alert(content.outerHTML)

    

 通過瀏覽器可以看到彈出框為<p id="p1">hello world </p>

和 <divid="d1"><p id="p1">hello world</p></div>

outerHTML指的是除了包含innerHTML的全部內容外, 還包含對象標籤本身。

總結說明


  innerHTML是符合W3C標準的屬性,而innerText只適用於IE瀏覽器(現在也適應chrome瀏覽器),因此,儘可能地去使用 innerHTML,而少用innerText,如果要輸出不含HTML標籤的內容,可以使用innerHTML取得包含HTML標籤的內容後,再用Regex去除HTML標籤,下面是一個簡單的符合W3C標準的樣本:

[html] view plain copy
  1. <html>  
  2.     <head><title>innerHTML</title></head>  
  3.     <body>  
  4.         <div id="d1"><p id="p1">hello world </p></div>  
  5.         <script>  
  6.             var content = document.getElementById("p1");  
  7.             alert(content.innerHTML.replace(/& lt;.+?>/gim,‘‘));  
  8.         </script>  
  9.     </body>  
  10. </html>  

彈出的為去掉了html標籤之後的內容,這是個在所有瀏覽器均可使用的方法。

innerHTML與innerText區別

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.