jQuery Snippets: outerHTML

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.

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

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.

7 Responses to “jQuery Snippets: outerHTML”

  1. zeal Says:

    but u can not use this function to set the outerHTML content, right?
    how can i replace the outerhtml content ?

  2. Brandon Aaron Says:

    Hey zeal,

    Just use the replace snippet I posted not too long ago. You can pass it HTML if you needed too.

    1. $('#myElement').replace('<div><p>test</p></div>');

    And the outerHTML snippet could be modified to be a setter also by implementing the replace snippet.

  3. Vijay Santhanam Says:

    Nice technique man!!

    This helped me out when I wanted the html of a cloned element.

  4. Sylvain Pointeau Says:

    how could we retrieve the outerHTML for a tag ?

  5. Sylvain Pointeau Says:

    for the tag tr (table row) ?

  6. Brandon Aaron Says:

    Sylvain, You just need to select the tr you want and then call .outerHTML() on it.

    1. $('tr').outerHTML();

  7. Sylvain Pointeau Says:

    it works with JQuery >= 1,2.3 thanks.

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>