jQuery replaceTagName

JavaScript performance comparison

Revision 2 of this test case created

Preparation code

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>
<script>
  (function($) {
    $.fn.replaceTagName_rev5 = function(replaceWith) {
      var tags = [],
          i = this.length;
      while (i--) {
        var newElement = document.createElement(replaceWith),
            thisi = this[i],
            thisia = thisi.attributes;
        for (var a = thisia.length - 1; a >= 0; a--) {
          var attrib = thisia[a];
          newElement.setAttribute(attrib.name, attrib.value);
        };
        newElement.innerHTML = thisi.innerHTML;

        $(thisi).after(newElement).remove();
        tags[i - 1] = newElement;
      }
      return $(tags);
    };
  })(window.jQuery);


  (function($) {
    $.fn.replaceTagName_rev4 = function(replaceWith) {
      var tags = [];
      for (var i = this.length - 1; 0 <= i; i--) {
        var newElement = document.createElement(replaceWith);
        newElement.innerHTML = this[i].innerHTML;
        $.each(this[i].attributes, function(j, attribute) {
          $(newElement).attr(attribute.name, attribute.value);
        });
        $(this[i]).after(newElement).remove();
        tags[i] = newElement;
      }
      return $(tags);
    };
  })(jQuery);



</script>
<script>
Benchmark.prototype.setup = function() {
    $('body').append('<div id="fixture"><div class="attr1" id="attr2" data-attr3="attr3"><span class="nest">Nested text<bold>!!</bold></span></div></div>');
};

Benchmark.prototype.teardown = function() {
    $('#fixture').remove();
};
</script>

Preparation code output

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
Revision 5
$('#fixture div').replaceTagName_rev5('span');
pending…
Revision 4
$('#fixture div').replaceTagName_rev4('span');
pending…
Current Solution
$("#fixture div").each(function(index) {
  var thisTD = this;
  var newElement = $("<span></span>");
  $.each(this.attributes, function(index) {
    $(newElement).attr(thisTD.attributes[index].name, thisTD.attributes[index].value);
  });
  $(this).after(newElement).remove();
});
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

0 comments

Add a comment