In jQuery, is the selector $('[id=foo]') less efficient than $('#foo')?
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]')
yeah,.
The fastest selector in jQuery is the ID selector $('#foo') because it maps directly to a native JavaScript method, getElementById()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With