我如何在'#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自FireFox 11(2012年3月)开始支持此功能
正如其他人指出的那样,这在FireFox中不起作用。如果您需要它在FireFox中工作,那么您可能想看看这个问题的答案:
在jQuery中,是否有任何类似于html()或text()的函数,但返回匹配组件的全部内容?
我喜欢用这个;
$('#container').prop('outerHTML');
var x = $('#container')[0].outerHTML;
$('#container').clone().wrapAll("<div/>").parent().html();
Update: outerHTML works on firefox now so use the other answer unless you need to support very old versions of firefox
Oldie but goldie...
Since user is asking for jQuery, I'm going to keep it simple:
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;
}
};
from http://forum.jquery.com/topic/jquery-getting-html-and-the-container-element-12-1-2010
Firefox doesn't support outerHTML, so you need to define a function to help support it:
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);
}
Then, you can use outerHTML:
var x = outerHTML($('#container').get(0));
$('#save').val(x);
var x = $($('div').html($('#container').clone())).html();
Simple solution with an example :
<div id="id_div">
<p>content<p>
</div>
Move this DIV to other DIV with id = "other_div_id"
$('#other_div_id').prepend( $('#id_div') );
Finish
文章标签:javascript , jquery
版权声明:本文为原创文章,版权归 javascript 所有,欢迎分享本文,转载请保留出处!
评论已关闭!