简体   繁体   中英

jQuery get html of container including the container itself

How do i get the html on '#container' including '#container' and not just what's inside it.

<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>

I have this which gets the html inside #container. it does not include the #container element itself. That's what i'm looking to do

var x = $('#container').html();
$('#save').val(x);

Check http://jsfiddle.net/rzfPP/58/

If you wrap the container in a dummy P tag you will get the container HTML also.

All you need to do is

var x = $('#container').wrap('<p/>').parent().html();

Check working example at http://jsfiddle.net/rzfPP/68/

To unwrap() the <p> tag when done, you can add

$('#container').unwrap();
var x = $('#container').get(0).outerHTML;

UPDATE : This is now supported by Firefox as of FireFox 11 (March 2012)

As others have pointed out, this will not work in FireFox. If you need it to work in FireFox, then you might want to take a look at the answer to this question : In jQuery, are there any function that similar to html() or text() but return the whole content of matched component?

var x = $('#container')[0].outerHTML;

我喜欢用这个;

$('#container').prop('outerHTML');
$('#container').clone().wrapAll("<div/>").parent().html();

更新:outerHTML现在可以在firefox上运行,所以除非你需要支持非常旧版本的firefox,否则请使用其他答案

Oldie but goldie...

Since user is asking for jQuery, I'm going to keep it simple:

var html = $('#container').clone();
console.log(html);

Fiddle here.

$.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

var x = $($('div').html($('#container').clone())).html();

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);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM