Reputation: 14960
Which would have better performance?
$('input[data-confirm],a[data-confirm],button[data-confirm]');
or
$('[data-confirm]');
Obviously the $('[data-confirm]')
version of the selector is more flexible, will it mean jQuery has to scan every single element in the page to see if it has the data-confirm attribute. Would I be better to use a class instead? I like using the data-confirm
because I can put this in the value.
<input type="submit" data-confirm="Are you sure you want to do this sir?" />
Upvotes: 0
Views: 121
Reputation: 91349
As @Guffa said, it really depends on the browser. Testing with Chrome 21.0.1180.89, the attribute equals selector is slightly faster:
Here's the jsperf: http://jsperf.com/attrvstag.
Upvotes: 1
Reputation: 402
Based on http://www.componenthouse.com/article-19 using the element selector is significantly faster than using the attribute selector on its own (there is a good discussion on selector performance here Good ways to improve jQuery selector performance?).
Personally I would go with the attribute selector first as like you say its more flexible, if your having performance issues you can then review this choice appropriately.
Upvotes: 1
Reputation: 700790
That depends on what the browser supports. If the selector can be handed off to the browser to be evaluated, either would be fast enough.
If not, the first one will be faster, as there is built in functions to find elements, that can be used by the sizzle engine. For the second one it would have to loop through all elements in the document.
Upvotes: 0
Reputation: 24566
Why not use a class AND the data-confirm
, this will allow you to be specific AND use the data-confirm
attribute to precisely target the exact element you want without having jquery look through everything else. This will make sure that regardless of browser your targeting will work faster. You can probably shave off a couple of nanoseconds off again if you use an id
rather than a class.
Upvotes: 3