jQuery: outer html()
JqueryJquery 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')
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>";