Reputation: 3281
If I know there is at most 1 such object in my DOM, should I always append :first to the selector to speed up the lookup? I'm assuming the selection engine will stop as soon as it finds 1 matching element, but I'm not sure if the filter actually slow things down a bit.
Upvotes: 7
Views: 338
Reputation: 723468
No, as :first
is not a standard CSS pseudo-class, and using it will cause your selector to not be passed to the native querySelectorAll()
DOM function implemented by supporting browsers (assuming you don't use any other jQuery-only selector syntax).
jQuery will take the entire selector and parse it by itself (using Sizzle, most likely), which is leagues slower than letting the browser do the work.
Upvotes: 6
Reputation: 16861
One practice that's almost true; the more selectors you specify, the more the engine has to validate.
So, in your case, if you know it only has one, don't specify it.
But with declaration below, say, 100, you won't even notice it.
Upvotes: 0