1. 程式人生 > >innerHTML與innerText區別

innerHTML與innerText區別

.get pre class 可能 如果 defined tle 標簽 ack

  document 對象中有innerHTML和innerText 兩個屬性, 這兩個屬性都是獲取document對象的文本內容的,這兩個屬性間有哪些區別呢?

示例1(一層嵌套各瀏覽器輸出)

<html>  
    <head><title>innerHTML</title></head>  
    <body>  
        <p id="p1">hello world </p>  
        <script>  
            var content 
= document.getElementById("p1"); alert(content.innerHTML); alert(content.innerText) </script> </body> </html>

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

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

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

示例2(多層嵌套各瀏覽器輸出)

<html>  
    <head><title>innerHTML</title></head>  
    <body>  
        <div id="d1"><p id="p1">hello world </p></div>  
        <script>  
            var content = document.getElementById("d1");  
            alert(content.innerHTML);  
            alert(content.innerText)  
        
</script> </body> </html>

通過IE瀏覽器打開,彈出內容為 <p id="p1">hello world </p> 和 hello world

通過 Firefox 瀏覽器打開,彈出內容為 <p id="p1">hello world </p> 和 undefined

通過 chrome 瀏覽器打開,彈出內容為 <p id="p1">hello world </p> 和 hello world

結論

通過上面兩個示例,可以看出:

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標簽的內容後,再用正則表達式去除HTML標簽,下面是一個簡單的符合W3C標準的示例:

<html>  
    <head><title>innerHTML</title></head>  
    <body>  
        <div id="d1"><p id="p1">hello world </p></div>  
        <script>  
            var content = document.getElementById("p1");  
            alert(content.innerHTML.replace(/&lt;.+?>/gim,‘‘));  //&lt;轉義字符 ‘<‘
</script> </body> </html>

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

參考:innerHTML與innerText區別

innerHTML與innerText區別