ProAnswers.org

jquery document.createElement equivalent?

I’m refactoring some old JavaScript code and there’s a lot of DOM manipulation going on.

var d = document;
var odv = d.createElement(“div”);
odv.style.display = “none”;
this.OuterDiv = odv;
var t = d.createElement(“table”);
t.cellSpacing = 0; t.className = “text”; odv.appendChild(t);
Is there a better way to do this using jQuery?
I’ve tried with:

var odv = $.create(“div”); $.append(odv); etc.
But I’m not sure this is any better.

this.$OuterDiv = $(’’)
.hide()
.append($(’’)
.attr({ cellSpacing : 0 })
.addClass(“text”)
)
;
I put together a small benchmark, and here’s roughly the results of repeating the above options 100,000 times:

[b]jQuery 1.4, 1.5, 1.6[/b]



           Chrome 11  Firefox 4   IE9 
        440ms      640ms    460ms 

div> 420ms 650ms 480ms
createElement 100ms 180ms 300ms

[b]jQuery 1.3[/b]



            Chrome 11 
         770ms 

div> 3800ms
createElement 100ms

[b]jQuery 1.2[/b]



            Chrome 11 
        3500ms 

div> 3500ms
createElement 100ms

I think it's no big surprise, but document.createElement is the fastest method.
Of course, before you go off and start refactoring your entire codebase,
remember that the differences we're talking about here (in all but the archaic versions of jQuery)
equate to about an extra 3 milliseconds per thousand elements.