imagine what we have something like this:

<div id="xxx"><p>Hello World</p></div>

if we call .html function in this way:

$("#xxx").html();

we will get:

<p>Hello World</p>

But i need to get:

<div id="xxx"><p>Hello World</p></div>

So, what i need to do? I think to add another wrapper around #xxx, but this is not a good idea.

4

Best Answer


Just use standard DOM functionality:

$('#xxx')[0].outerHTML

Or a bit simpler with .prop():

$('#xxx').prop('outerHTML')

outerHTML is well supported - verify at Mozilla or caniuse.

Create a temporary element, then clone() and append():

$('<div>').append($('#xxx').clone()).html();

No siblings solution:

var x = $('#xxx').parent().html();alert(x);

Universal solution:

// no cloning necessary var x = $('#xxx').wrapAll('<div>').parent().html(); alert(x);

Fiddle here: http://jsfiddle.net/ezmilhouse/Mv76a/

If you don't want to add a wrapper, you could just add the code manually, since you know the ID you are targeting:

var myID = "xxx";var newCode = "<div id='"+myID+"'>"+$("#"+myID).html()+"</div>";