Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are data attribute css selectors faster than class selectors?

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")?

like image 772
Vlad Nicula Avatar asked Sep 19 '12 14:09

Vlad Nicula


People also ask

Which CSS selector is faster?

popupbutton is the fastest.

Are attribute selectors slow?

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.

Which selector is best in CSS?

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.


2 Answers

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

like image 113
BLSully Avatar answered Sep 21 '22 04:09

BLSully


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:

  • 31% faster in Chrome 27.0.1453
  • 140% faster in Firefox 15.0.1
  • 131% faster in Firefox 21.0
  • 1,267% faster in IE 9.0
  • 1,356% faster in IE 10.0
like image 34
Zac Avatar answered Sep 17 '22 04:09

Zac