jQuery: outer html()

Jquery

Jquery Problem Overview


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.

Jquery Solutions


Solution 1 - Jquery

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.

Solution 2 - Jquery

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

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

Solution 3 - Jquery

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/

Solution 4 - Jquery

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionvorobeyView Question on Stackoverflow
Solution 1 - JqueryAndyView Answer on Stackoverflow
Solution 2 - JqueryDavid TangView Answer on Stackoverflow
Solution 3 - JqueryezmilhouseView Answer on Stackoverflow
Solution 4 - JquerySteve KellyView Answer on Stackoverflow