jQuery: outerHTML

The outerHTML property (IE only) could sometimes be very handy, especially if you’re trying to replace an element entirely. Brandon Aaron has very kindly given us a outerHTML plugin that does half the job as it doesn’t support replacements. The following code snippet fills in the blanks:

jQuery.fn.outerHTML = function(s) {
return (s)
? this.before(s).remove()
: jQuery("<p>").append(this.eq(0).clone()).html();
}

To get the outerHTML value of an element do this…

$('#myTag').outerHTML();

To replace #myTag entirely do this…

$('#myTag').outerHTML("<p>My brand new #myTag.</p>");

Hope this helps someone :)

Update: There’s now a demo page.