2010-03-20 33 views
11

如何在JavaScript中使用outerHTML?謝謝如何在JavaScript中使用outerHTML?

+1

您可能想要檢查此:http://stackoverflow.com/questions/2474605/how-to-convert-a-htmlelement-to-a-string – 2010-03-20 14:49:14

+0

可能重複的[如何將HTMLElement轉換爲字符串](https://stackoverflow.com/questions/2474605/how-to-convert-a-htmlelement-to-a-string) – Graham 2017-10-01 15:17:15

回答

10

outerHTML是包含元素本身的元素的HTML。將其與元素的innerHTML進行對比,元素是元素打開和關閉標記中包含的HTML。根據定義,沒有開放標籤和結束標籤的元素沒有innerHTML。

當您要完全替換元素及其內容時,請使用outerHTML。當你只想替換元素的內容時使用innerHTML。

7

outerHTML是元素的非標準Internet Explorer屬性。它返回元素的html及其子元素。在某些情況下,它可以設置爲用html字符串完全替換元素。

+6

一年過去了,Chrome和Safari似乎也實現了此功能。但是,在撰寫本文時,Firefox不支持它。 – 2011-08-19 10:34:55

+10

在[Firefox 11](https://developer.mozilla.org/en/Firefox_11_for_developers)中添加了對[outerHTML](https://developer.mozilla.org/en/DOM/element.outerHTML)的支持。 – 2012-04-10 16:58:14

11
function getHTML(node){ 
    if(!node || !node.tagName) return ''; 
    if(node.outerHTML) return node.outerHTML; 

    // polyfill: 
    var wrapper = document.createElement('div'); 
    wrapper.appendChild(node.cloneNode(true)); 
    return wrapper.innerHTML; 
} 
+0

有趣的想法。然而,因爲大多數不支持outerHTML的瀏覽器確實支持HTMLElement原型,我想知道是否更容易實現僞本機? – scunliffe 2010-03-20 15:48:39