Create nested DOM structure (jquery vs native js)

Benchmark created by Parag on


Description

jQuery way : create a document-fragment of the complex html string (is it appended to the document after creation?) and then modify properties while traversing using jquery methods. Finally its appended to the target element (i hope i am understanding this correctly).

Native js way: The complex dom structure to be created is laid out in a hash first. The hash is then passed through a 'create' method that recursively generates each tag (and its attributes) using native js methods and appends to a document-fragment which is then appended to the target element

Preparation HTML

<style type="text/css">
  h3{margin: 15px 0 0;color:rgb(120,120,120);}
  li{ margin: 2px 0;overflow: auto; border:1px solid rgb(240,240,240);}
  .left{ float: left;margin:0 5px 0 0; color: gray;}
  .right{float: right; color: orange;}
</style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<h3>Recursive DOM creation</h3>
<ul id="append-native-here">
</ul>

<h3>jQuery DOM creation</h3>
<ul id="append-jquery-here">
</ul>
<script>
  var myApp = {};
  myApp.dom = {
   tag: 'li',
   class: 'selected',
   title: 'A list item',
   content: [{
    tag: 'span',
    text: 'I am a span',
    class: 'left'
   },
   {
    tag: 'span',
    class: 'right',
    text: 'I am a second span'
   },
   {
    tag: 'input',
    type: 'hidden',
    name: 'selector_object[]',
    value: 10
   }]
  };
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
Recursive DOM creation
function _createTag(obj) {
 var tag = document.createElement(obj.tag);
 for (var attr in obj) {
  if (attr !== 'tag' && attr !== 'text' && attr !== 'content') {
   tag.setAttribute(attr, obj[attr]);
  }
  if (attr === 'text') {
   tag.appendChild(document.createTextNode(obj[attr]));
  }
 }
 if (obj.hasOwnProperty('content')) {
  for (var elem = 0, len = obj.content.length; elem < len; elem++) {
   tag.appendChild(_createTag(obj.content[elem]));
  }
 }
 return tag;
} // private create function ends
myApp.create = function(domObj) {
 var fragment = document.createDocumentFragment();
 fragment.appendChild(_createTag(domObj));
 return fragment;
};

document.getElementById('append-native-here').appendChild(myApp.create(myApp.dom));
ready
jQuery's DOM creation
jQuery("<li><span></span><span></span><input type='hidden'></input></li>").addClass('selected').attr('title', 'A list item').find("span:first-child").addClass("left").html("I am a span").end().find("span:nth-child(2)").addClass("right").text("I am a second span").end().find("input").attr("name", "some_hidden_input").val(10).end().appendTo("#append-jquery-here");
ready

Revisions

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