jQuery outerHTML Snippet

outerHTML is a property that is provided by Internet Explorer that returns the full HTML of an element (including start and end tags). In jQuery, the html() function returns the innerHTML of an element, which is just the HTML inside the element (not including the start and end tags).

There came a time that I wanted to get the outerHTML of an element, and I found that Brandon Aaron shared a jQuery code snippet that does this exactly. It does the trick for most cases, but there was one problem that I ran into. I wanted to get the outerHTML of an element inside of an iframe, and I got a 'Permission Denied' error in Internet Explorer.

The problem was that it was appending an element belonging to the iframes 'contentDocument' into an element belonging to the global 'document' element.

Using the jQuery(html, ownerDocument) overload of the jQuery core function, this error was fixed:

$.fn.outerHTML = function() {
    var doc = this[] ? this[].ownerDocument : document;
    return $('<div>', doc).append(this.eq().clone()).html();
};

Comments

  1. Tim Farland Says:

    There are definitely uses for outerHTML. This should be in the jQuery core. Well done dealing with that esoteric permission stuff!

  2. Joseph Twumasi Says:

    Really great jquery snippet which helps me alot.

Comments are closed. Please contact me instead.