outerHTML vs jQuery clone hack (v9)

Revision 9 of this benchmark created by Claw on


Preparation HTML

<div id="test">
  <p>
    foo
  </p>
  <p>
    bar
  </p>
</div>
<script src="//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);

Test runner

Ready to run.

Testing in
TestOps/sec
outerHTML
var x = document.getElementById('test').outerHTML;
ready
jQuery Clone-then-Wrap
var x = $('#test').clone().wrap('<div>').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
var x = $('#test').outerHTML();
ready
combo
var x = $('#test')[0].outerHTML;
ready
jQuery wrap-then-unwrap
var $el = $('#test');
var x = $el.wrap('<div>').parent().html();
$el.unwrap()
ready

Revisions

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