skip to content

jQuery Snippets: outerHTML

1 min read

Internet Explorer provides an interesting property called outerHTML. The outerHTML property returns the HTML that composes the whole element, unlike innerHTML which returns the HTML that composes of what is inside the element. None of the other browsers implemented this non-standard property but it can be useful sometimes. So here is a cross browser implementation of outerHTML using jQuery.

jQuery.fn.outerHTML = function() {
    return $('<div>').append( this.eq(0).clone() ).html();
};

The way it works is to take the first matched element in the jQuery collection, clone it, append that clone to a newly created div and return that div’s html.

You can download the source code and see an example here.