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.
Mozillas Writing efficient CSS tl;dr for this:
Universal rules
All other rules fall into this category.
Example
[hidden="true"] {…} /* A universal rule */` * {…} /* A universal rule */ tree > [collapsed="true"] {…} /* A universal rule */
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 ;) ).
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