jQuery.css() vs. CSS classes and jQuery.addClass()/jQuery.removeClass()

jQuery.css() vs. CSS classes and jQuery.addClass()/jQuery.removeClass()
0.0 0


I’m wondering if it’s better to run jQuery.css() calls with object arguments to apply changes to multiple CSS properties, or if it’s better to create alternate classes (ex. h1a, h1b, h1c), and then run jQuery.removeClass(h1a) along with jQuery.addClass(h1b). It seems to me that creating the CSS classes and switching them out as needed creates cleaner code that is easier to understand, but which approach is better for performance?
Is calling jQuery.css() with an object argument to apply changes to multiple CSS properties equivalent to running the jQuery function multiple times with the (string, string) arguments?

In case I’m explaining this poorly, when I say running jQuery.css() with an object argument, I’m talking about a call that looks like this:

$("#h1").css( { 'font-size': '24px', 'font-weight': '450' } );

As opposed to something that looks like this:

$("#h1").css('font-size', '24px');
$("#h1").css('font-weight', '450');

Thanks for any help on this matter


In my opinion it is better to add and remove classes. It keeps your JS/JQuery code cleaner and likely a lot easier to understand.

.addClass("main-header-red") is easier to understand than .css({'color' : '#ff0000'} {...}) or the like.

Another point you asked about is performance. I found a test that gives you an idea. It’s here


Thanks for the advice. That test was really cool to look at, but from what I can tell it seems to show that the “Plain JS replace classes” approach was far faster than either the “Apply CSS” or “Remove and Add classes” approaches. Both of those slower approaches used jQuery, while the “Plain JS Replace Class” approach worked with the DOM element. Is this because working with DOM elements is always better for performance? Or is there something about that code that I’m not seeing?
The JS code that had the best performance (operations/second) that I’m talking about is:

var elem = document.getElementsByTagName('div')[0];
elem.className = elem.className.replace('otherClass', 'newClass');


@Levester Jquery is built with Javascript, but there’s more overhead involved when Jquery is used so it can be slower.

Both will query the DOM but with JQuery there’s more going on behind the scenes.