La proprietà non standard outerHTML
restituisce la marcatura dell'elemento a cui è legata ad eccezione dei suoi contenuti. In pratica questa proprietà restituisce un'istantanea dell'elemento sotto forma di stringa, compresi i suoi attributi. Alcuni browser non implementano questa proprietà. Possiamo emularne il funzionamento con jQuery.
Possiamo creare il seguente plugin:
(function ($) {
$.fn.outerHTML = function () {
var element = this,
elem = element[0],
tag = elem.tagName.toLowerCase(),
attrs = elem.attributes,
html = '<' + tag;
if (elem.hasAttributes()) {
for (var i = 0; i < attrs.length; i++) {
var attr = attrs[i];
html += ' ' + attr.name + '="' + attr.value + '"';
}
}
html += '></' + tag + '>';
return html;
};
})(jQuery);
Esempio d'uso:
$('#outer').click(function () {
alert($('#test').outerHTML());
});