JS基礎篇--innerHTML,innerText,outerHTML,textContent的用法與區別

示例html代碼:javascript

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

得到id爲test的DOM對象,下面就不一一獲取了。html

var test = document.getElementById('test');

test.innerHTML

描述:也就是從對象的起始位置到終止位置的所有內容,包括Html標籤。java

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

test.innerText

描述:從起始位置到終止位置的內容, 但它去除Html標籤 。瀏覽器

上例中的test.innerText的值也就是「test1 test2」, 其中span標籤去除了。spa

test.outerHTML

描述:除了包含innerHTML的所有內容外, 還包含對象標籤自己。code

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

完整示例:對象

<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)">inerText內容</a>
<a href="javascript:alert(test.outerHTML)">outerHTML內容</a>

結果:ip

//test.innerHTML結果:<span style="color:red">test1</span> test2
//test.innerText結果:test1 test2
//test.outerHTML結果:<div id="test"><span style="color:red">test1</span> test2</div>

test.textContent

描述:textContent 屬性設置或返回指定節點的文本內容,以及它的全部後代。

提示:有時,此屬性可用於取代 nodeValue 屬性,可是請記住此屬性同時會返回全部子節點的文本。

獲得的結果跟innerText的結果是同樣的。

註釋:Internet Explorer 8 以及更早的版本不支持此屬性。

兼容性

innerHTML全部瀏覽器兼容;innerTextouterHTML雖然主流瀏覽器,如谷歌,火狐,IE7-IE11,QQ等都已支持(這裏提到的谷歌火狐等都是最新瀏覽器的版本),可是W3C的標準屬性就是innerHTML,所以,儘量地去使用innerHTML,而少用innerTextouterHTML

相關文章
相關標籤/搜索