$.fn.outerHTML
Adding outerHTML support to jQuery
HTML
<div id="colors">
<span>red</span>
<span>blue</span>
<span>PURPLE!!!!!</span>
</div>
JavaScript
$.fn.extend({
outerHTML: function(htmlString)
{
if (!this.length) {
return;
}
if (htmlString) {
return this.replaceWith(htmlString);
}
return this[0].outerHTML || (function(el) {
var attrs = el.attributes,
i = 0,
n = attrs.length,
name = el.nodeName.toLowerCase(),
attrlist = '';
for (; i != n; ++i) {
attrlist += ' ' + attrs[i].name + '="' + attrs[i].value + '"';
}
return '<' + name + attrlist + '>' + el.innerHTML + '</' + name + '>';
}(this[0]));
}
});
console.log('native outerHTML: ' + $('#colors')[0].outerHTML);
console.log('jQuery cross-browser outerHTML: '+ $('#colors').outerHTML());