[javascript] 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/

This question is related to javascript jquery

The answer is


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


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

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.


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


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?


I like to use this;

$('#container').prop('outerHTML');

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