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;

Reference URL


  1. 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 ?

    • Nao
      Permalink to comment#

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

  2. 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. nicolas
    Permalink to comment#

    what is the el used here? lost…

Leave a Comment

Posting Code

We highly encourage you to post problematic HTML/CSS/JavaScript over on CodePen and include the link in your post. It's much easier to see, understand, and help with when you do that.

Markdown is supported, so you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences like this:

  function example() {
    element.innerHTML = "<div>code</div>";

We have a pretty good* newsletter.