outerHTML jQuery Plugin

innerHTML() is native and returns the contents of a DOM node (e.g. <span>I live inside a div.</span>. outerHTML() is not, which would include the current DOM node (e.g. <div><span>I live inside a div.</span></div>). This is a chain-able jQuery version of doing that.

$.fn.outerHTML = function(){
    // IE, Chrome & Safari will comply with the non-standard outerHTML, all others (FF) will have a fall-back for cloning
    return (!this.length) ? this : (this[0].outerHTML || (
          var div = document.createElement('div');
          var contents = div.innerHTML;
          div = null;
          return contents;


  1. User Avatar
    Ben Reinhart
    Permalink to comment#

    Am I missing something, seems like this is unnecessarily overcomplicating things, why couldn’t it be written like:
    https://gist.github.com/3707775 ?

    • User Avatar
      Permalink to comment#

      The snippet on this page returns a chain-able jQuery object.

  2. User Avatar
    Ben Reinhart
    Permalink to comment#

    That’s not true, the only time this would return a chainable jquery object is if there are no elements in the set:

    return (!this.length) ? this : (this[0].outerHTML || (function(){ ... })());

    if the jquery set is empty (length 0) then it returns this which is the jquery object that is chainable. Otherwise it tries to return the native html outerHTML propery. If the native html outerHTML property is null, then it calls the function, which also returns a string, not a jquery object.

    This snippet also doesn’t perform this on each element of the set, it only performs it on the first element (this[0]). However, that makes sense, it would be really weird to return an array of strings of html which would not be jquery objects.

  3. User Avatar
    Permalink to comment#

    what is the el used here? lost…

Leave a Comment

Posting Code!

You may write comments in Markdown. This makes code easy to post, as you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences (```) with double new lines before and after.

Code of Conduct

Absolutely anyone is welcome to submit a comment here. But not all comments will be posted. Think of it like writing a letter to the editor. All submitted comments will be read, but not all published. Published comments will be on-topic, helpful, and further the discussion or debate.

Want to tell us something privately?

Feel free to use our contact form. That's a great place to let us know about typos or anything off-topic.