Grow your CSS skills. Land your dream job.

Last updated on:

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 || (
      function(el){
          var div = document.createElement('div');
          div.appendChild(el.cloneNode(true));
          var contents = div.innerHTML;
          div = null;
          return contents;
    })(this[0]));
 
}

Reference URL

Comments

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

Markdown is supported in the comment area, so you can write inline code in backticks like `this` or multiline blocks of code in in triple backtick fences like this:

```
<div>Example code</div>
```

You don't need to escape code in backticks, Markdown does that for you. If anything screws up, contact us and we can fix it up for you.

*May or may not contain any actual "CSS" or "Tricks".