Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In jQuery, is the selector $('[id=foo]') less efficient than $('#foo')?

In jQuery, is the selector $('[id=foo]') less efficient than $('#foo')?

like image 220
jbyrd Avatar asked Aug 18 '10 17:08

jbyrd


2 Answers

  • short and easy: YES !

  • long story (still short actually)

     $('[id=foo]')
    

    uses Sizzle (css query engine) to select the element whereas

     $('#foo') 
    

    directly calls getElementById.

To have a really long story, here we go: $('[id=foo]') is a synonym for $('*:[id=foo]') which uses the universal selector. That means, it querys ALL nodes within your markup and then looks which of those have the id === foo (which then hopefully will only match one element, IDs = unique). That of course, is costly, pretty costly. And that is why you never ever ever ever should write a selector like this! Always fully qualify this if possible, like $('span:[id=foo]')

like image 58
jAndy Avatar answered Nov 15 '22 00:11

jAndy


yeah,.

The fastest selector in jQuery is the ID selector $('#foo') because it maps directly to a native JavaScript method, getElementById()

like image 36
ovais.tariq Avatar answered Nov 15 '22 02:11

ovais.tariq