Are there any differences in performance (or others) regarding attributes or classes?

I am interested in adding classes or adding attributes to elements to dynamically style them.

An agreement to apply CSS properties to specific elements that satisfy certain parameters is usually done by applying a class to that element. For example, if I click on a button, we can say that this button is in an active state - I could choose to apply a special class to it, for example:

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

CSS will be as simple as:

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

My approach is different, and I'm curious if there is any noticeable difference between the two. I apply attributes to elements instead of classes, for example:

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

With CSS as follows:

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

I am wondering if there are any reasons why I should not do this, if this is a bad agreement or something else, and if there is any performance difference in this method. Mostly just curious, but also interesting, for example, if you use queries like $(".button[active]") , are less effective than $(".button .active") .

+6
source share
2 answers

Someone created a performance test to answer a similar question about stack overflow .

http://jsperf.com/id-vs-class-vs-tag-selectors/2

It seems that the class selector is much faster than the attribute selector, although apparently the amount varies depending on the browser.

+1
source

Mozillas Writing Effective CSS tl; dr for this:

  • 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. Do not use universal selectors.

Avoid universal rules

Make sure the rule is not in the universal category!

But there is an active discussion on css selectors .

Most interestingly, CSSLint considers the prohibition of selecting unqualified attributes for performance reasons.

Therefore, I must adhere to class selectors that show that they are executed (when, as always, they are not abused;)).

+2
source

All Articles