A few months ago this article pointed out that classes could actually be avoided all together from website development.
My question is, how efficient are the data selectors compared to class selectors?
A simple example would be to compare querying for elements with data-component='something'
versus elements with class='class1 class2 something anotherClass'
.
The [data-<attr>='<value>']
selector will check the value as a whole versus the class string that should be split. With this in mind, data atributes should be faster.
So, to refine the question, in the case of CSS, are we better off with class selector or data selector? And from a javascript point of view, will jQuery("[data-component='something']")
be more efficient than jQuery(".something")
?
popupbutton is the fastest.
The table outlines that attribute selectors are approximately 3x slower compared to standard classes. Relying on attribute selectors also requires more characters to target an element. It's better to define short and concise class names to keep your stylesheet small.
Class selector is the most useful common selector used by the developers. You can define the class selector using period (.) followed by the class name. It gives styling to all elements with a specified class attribute.
I wouldn't call it conclusive, but it does appear class selectors are faster... I just put this together for a quickie test.
http://jsperf.com/data-selector-performance
EDIT:
Based on Vlad's and my jsperf tests... if performance is a concern (especially IE)... classes are still the way to go
After checking out BLSully's answer and the test page he provided, here are the actual figures for comparison.
jQuery class selector performance vs jQuery data attribute selector performance operations per second:
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