jbyrd
jbyrd

Reputation: 5595

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

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

Upvotes: 6

Views: 569

Answers (2)

jAndy
jAndy

Reputation: 236092

  • 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]')

Upvotes: 16

ovais.tariq
ovais.tariq

Reputation: 2625

yeah,.

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

Upvotes: 1

Related Questions