![](/img/trans.png)
[英]How to load html using jQuery load() function from the anchor inside the container itself?
[英]jQuery get html of container including the container itself
我如何獲得'#container'上的html,包括'#container',而不僅僅是內部的內容。
<div id="container">
<div id="one">test 1 </div>
<div id="two">test 2 </div>
<div id="three">test 3 </div>
<div id="four">test 4 </div>
</div>
我有這個獲取#container內的html。 它不包括#container元素本身。 這就是我想要做的
var x = $('#container').html();
$('#save').val(x);
如果將容器包裝在虛擬P
標簽中,您也將獲得容器HTML。
你需要做的就是
var x = $('#container').wrap('<p/>').parent().html();
查看http://jsfiddle.net/rzfPP/68/上的工作示例
要在完成后unwrap()
<p>
標記,您可以添加
$('#container').unwrap();
var x = $('#container').get(0).outerHTML;
更新 :自FireFox 11開始支持Firefox(2012年3月)
正如其他人所指出的,這在FireFox中不起作用。 如果你需要它在FireFox中工作,那么你可能想看看這個問題的答案: 在jQuery中,是否有任何類似於html()或text()的函數但是返回匹配組件的全部內容?
var x = $('#container')[0].outerHTML;
我喜歡用這個;
$('#container').prop('outerHTML');
$('#container').clone().wrapAll("<div/>").parent().html();
更新:outerHTML現在可以在firefox上運行,所以除非你需要支持非常舊版本的firefox,否則請使用其他答案
Oldie但是goldie ......
由於用戶要求jQuery,我將保持簡單:
var html = $('#container').clone();
console.log(html);
$.fn.outerHtml = function(){
if (this.length) {
var div = $('<div style="display:none"></div>');
var clone =
$(this[0].cloneNode(false)).html(this.html()).appendTo(div);
var outer = div.html();
div.remove();
return outer;
}
else {
return null;
}
};
來自http://forum.jquery.com/topic/jquery-getting-html-and-the-container-element-12-1-2010
var x = $($('div').html($('#container').clone())).html();
Firefox不支持outerHTML ,因此您需要定義一個函數來幫助支持它:
function outerHTML(node) {
return node.outerHTML || (
function(n) {
var div = document.createElement('div');
div.appendChild( n.cloneNode(true) );
var h = div.innerHTML;
div = null;
return h;
}
)(node);
}
然后,您可以使用outerHTML:
var x = outerHTML($('#container').get(0));
$('#save').val(x);
簡單解決方案的一個例子:
<div id="id_div">
<p>content<p>
</div>
將此DIV移動到id =“other_div_id”的其他DIV
$('#other_div_id').prepend( $('#id_div') );
完
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.