jQuery document.createElement equivalent?

后端 未结 14 1850
暖寄归人
暖寄归人 2020-11-22 05:41

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.di         


        
14条回答
  •  耶瑟儿~
    2020-11-22 06:23

    Here's your example in the "one" line.

    this.$OuterDiv = $('
    ') .hide() .append($('
    ') .attr({ cellSpacing : 0 }) .addClass("text") ) ;

    Update: I thought I'd update this post since it still gets quite a bit of traffic. In the comments below there's some discussion about $("

    ") vs $("
    ")
    vs $(document.createElement('div')) as a way of creating new elements, and which is "best".

    I put together a small benchmark, and here are roughly the results of repeating the above options 100,000 times:

    jQuery 1.4, 1.5, 1.6

                   Chrome 11  Firefox 4   IE9
    
    440ms 640ms 460ms
    420ms 650ms 480ms createElement 100ms 180ms 300ms

    jQuery 1.3

                    Chrome 11
    
    770ms
    3800ms createElement 100ms

    jQuery 1.2

                    Chrome 11
    
    3500ms
    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.


    Update 2

    Updated for jQuery 1.7.2 and put the benchmark on JSBen.ch which is probably a bit more scientific than my primitive benchmarks, plus it can be crowdsourced now!

    http://jsben.ch/#/ARUtz

提交回复
热议问题