innerHTML與innerText區別,innerhtmlinnertext
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標籤的內容後,再用Regex去除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,''));</script></body></html>
彈出的為去掉了html標籤之後的內容,這是個在所有瀏覽器均可使用的方法。