Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there any performance (or otherwise) differences concerning attributes vs. classes? [duplicate]

I'm curious about adding classes vs. adding attributes to elements in order to dynamically style them.

The convention for applying CSS properties to certain elements that satisfy specific parameters is usually done by applying a class to that element. For instance if I click on a button, that button can be said to be in an active state - I could choose then to apply a custom class to it on click, like so:

$(".button").click(function(){
    $(this).addClass("active");
});

The CSS would be as simple as:

.button.active {
    transform: scale(1.5);
}

My approach is different, and I'm curious as to whether there's any appreciable difference between the two. I apply attributes to the elements instead of classes, like so:

 $(".button").click(function(){
     $(this).attr("active", true);
 });

With the CSS like this:

.button[active] {
    transform: scale(1.5);
}

I'm wondering if there are any reasons why I shouldn't do this i.e. if this is a bad convention or whatever and if there's any performance difference in this method. Mostly just curious, but also wondering if using queries like $(".button[active]") turn out to be less performant than $(".button .active"), for example.

like image 654
jonny Avatar asked Aug 11 '15 15:08

jonny


1 Answers

Mozillas Writing efficient CSS tl;dr for this:

  1. attribute selectors are universal selectors

Universal rules

All other rules fall into this category.

Example

[hidden="true"] {…} /* A universal rule */`
* {…}     /* A universal rule */
tree > [collapsed="true"] {…} /* A universal rule */
  1. Don't use universal selectors.

Avoid universal rules

Make sure a rule doesn’t end up in the universal category!

But there is active discussion on css selectors.

Most interestingly, CSSLint considers disallowing unqualified attribute selectors for performance reasons.

I would therefore stick to class selectors which have shown to be performant (when, as always, not misused ;) ).

like image 129
Dominik Schreiber Avatar answered Sep 18 '22 03:09

Dominik Schreiber