views:

85

answers:

2

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

+15  A: 
  • 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]')

jAndy
Ahh heres a sub-question for you then jAndy - is `$('span:[id=foo]')` just longhand for `$(span#foo)` or a different selector altogether?
HurnsMobile
@HurnsMobile: Not at all. `$('span:[id=foo]')`. I actually would recommend to have a look over the jQuery init code here. jQuery does parse some selector expressions to a direct call of `getElementById` or `getElementsByTagName`, I think `$(span#foo)` is one of those. So it's definatly faster than `$('span:[id=foo]')`. That expression will go into Sizzle and that obviously takes longer than one of the above mentioned methods.
jAndy
Very informative, thanks a lot. The reason I was considering using something besides $("#foo") to target an id is because the id I was targeting had a period in it, which is obviously problematic as jQuery would interpret this as an id and a class. So by using $("[id=Address.State]"), for example, I could get around the issue. Another way to get around it is to double escape the period as in $("#Address\\.State"), but I thought the double escape might be less readable. However, given the efficiency loss you pointed out, I'd probably use that anyway.
jbyrd
+1  A: 

yeah,.

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

ovais.tariq