innerHTML、outerHTML、innerText、outerText的用法與

來源:互聯網
上載者:User

標籤:style   color   使用   java   div   sp   c   html   ad   

完整樣本:

<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)">innerText內容</a> 

<a href="javascript:alert(test.outerHTML)">outerHTML內容</a> 

 

test.innerHTML: 

也就是從對象的起始位置到終止位置的全部內容,包括Html標籤。

上例中的

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

 

 test.innerText: 

 從起始位置到終止位置的內容, 但它去除Html標籤

 上例中的text.innerText的值也就是“test1 test2”, 其中span標籤去除了。

 

test.outerHTML: 

 除了包含innerHTML的全部內容外, 還包含對象標籤本身。上例中的text.outerHTML的值也就是<div id="test"><span style="color:red">test1</span> test2</div> 

 

test.outerText: 設定(包括標籤)或擷取(不包括標籤)對象的文本。

 

特別說明:

innerHTML是符合W3C標準的屬性,而innerText只適用於IE瀏覽器,因此,儘可能地去使用innerHTML,而少用innerText,如果要輸出不含HTML標籤的內容,可以使用

innerHTML取得包含HTML標籤的內容後,再用Regex去除HTML標籤,例

<a href="javascript:alert(document.getElementById(‘test‘).innerHTML.replace(/<.+?>/gim,‘‘))">

 

innerHTML和outerHTML、innerText與outerText的不同之處在於:

 1)、innerHTML與outerHTML在設定對象的內容時包含的HTML會被解析,而innerText與outerText則不會。

 2)、在設定時,innerHTML與innerText僅設定標籤內的文本,而outerHTML與outerText設定包括標籤在內的文本。

innerHTML、outerHTML、innerText、outerText的用法與

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.