Which is faster and why? Selecting div (for plugin needs) by $('div[data-something]')
or $('div.something')
? I lean towards the former since it's "cleaner".
Based on this SO question I know I shouldn't be using both. However I didn't find out whether there is a difference between these.
In Chrome 16 at least, there is no difference. However, if you make the class selector less specific ($(".test")
for example), it does outperform the other methods:
That was somewhat unexpected, because as ShankarSangoli mentions, I thought the div.test
class selector would be faster.
It will vary by browser. Nearly all browsers now support querySelectorAll
, and jQuery will use it when it can. querySelectorAll
can be used with attribute presence selectors, so if it's there jQuery doesn't have to do the work, it can offload it to the engine.
For older browsers without querySelectorAll
, jQuery will obviously have to do more work, but even IE8 has it.
As with most of these things, your best bet is:
Don't worry about it until/unless you see a problem, and
If you see a problem, profile it on the browsers you intend to support and then make an informed decision.
Selecting by class is always faster than attribute selector because jQuery tries to use the native getElementByCalssName
first if supported by browsers. If not it uses the querySelector
which uses css selectors to find the elements within the page.
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