2011-10-27 32 views
0

可能重複:
Get selected element's outer HTMLjQuery的HTML()函數 - 如何將選擇的Html

我懷疑這是一個非常愚蠢的問題,但是當你調用HTML()函數在JQuery中,它返回選中的節點內部的Html。無論如何在返回的Html中包含選定的音符?例如以下HTML

<div class="demo-container"> 
    <div class="demo-box">Demonstration Box</div> 
</div> 

此調用$('div.demo-container').html();返回

<div class="demo-box">Demonstration Box</div> 

如何獲得它返回

<div class="demo-container"> 
    <div class="demo-box">Demonstration Box</div> 
</div> 

感謝您的幫助!

回答

2

你可以在一個無聊的div包裹它的一個副本,並得到了HTML:

var str = $('div.demo-container').clone().wrap('<div/>').parent().html(); 
+0

ugh divs SO 2010;) – MorganTiley

1

寫這個擴展,例如,從here

jQuery.fn.outerHTML = function(s) { 
    return (s) 
    ? this.before(s).remove() 
    : jQuery("&lt;p&gt;").append(this.eq(0).clone()).html(); 
} 

然後,當你想使用它:

$('#myTag').outerHTML(); 
0
$('div.demo-container').parent().html() //Only works in this specific situation 

$('div.demo-container')[0].outerHTML; //Only works in IE and Chrome 
+0

不outerHTML只有IE屬性? – MorganTiley

+0

'.parent()。html()'如果'div.demo-container'具有兄弟,則會給出錯誤的結果。 – Blazemonger

+0

@MorganTiley它也適用於Chrome瀏覽器,似乎並不支持firefox – Esailija

0

這可能會爲你工作:

$('div.demo-container').parent().html(); 
+0

如果'div.demo-container'有兄弟,會給出錯誤的結果。 – Blazemonger

+0

給他的例子正確的結果:) – jbabey