outerHTML vs jQuery clone hack (v5)

Revision 5 of this benchmark created by gtournie on


Preparation HTML

<div id="test">
  <p>
    foo
  </p>
  <p>
    bar
  </p>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>

Setup

(function($) {
        $.fn.getHTML= function(){
        var txt, ax, el= document.createElement("div"),
            who = $(this)[0];
        el.appendChild(who.cloneNode(false));
        txt= el.innerHTML;
            ax= txt.indexOf('>')+1;
            txt= txt.substring(0, ax)+who.innerHTML+ txt.substring(ax);
        el= null;
        return txt;
    }
    })(jQuery);
    
    
    (function($){
        $.fn.outerHTML = function() {
                var a = this.get(0).outerHTML;
                return a ? a : $('<p/>').append(this.clone()).html();
        }
    })(jQuery);
    
    // gtournie's jQuery plugin
    (function($) {
    
      var DIV = document.createElement("div"),
          outerHTML;
    
      if ('outerHTML' in DIV) {
        outerHTML = function(node) {
          return node.outerHTML;
        };
      } else {
        outerHTML = function(node) {
          var div = DIV.cloneNode();
          div.appendChild(node.cloneNode(true));
          return div.innerHTML;
        };
      }
    
      $.fn.outerHTML2 = function() {
        return this.length ? outerHTML(this[0]) : void(0);
      };
    
    })(jQuery);

Test runner

Ready to run.

Testing in
TestOps/sec
native outerHTML
var x = $('#test')[0].outerHTML;
ready
jQuery Clone-then-Wrap
var x = $('#test').clone().wrap('<p>').parent().html();
ready
jQuery create-and-append
var x = $('<p/>').append($('#test').clone()).html()
ready
Vanilla JS plugin
var x = $('#test').getHTML();
ready
Lightweight Feature-Detection Plugin (FF > 11 ONLY!)
var x = $('#test').outerHTML();
ready
gtournie's jQuery plugin
var x = $('#test').outerHTML2();
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.