Here are a couple ways to apply CSS styling to an element using jQuery that we’re all familiar with:
$('.box').css({'background':'#fff', 'color':'#000'});
Or, we can use a combination of jQuery and external CSS to elicit the same effect:
.box.deco { background:#fff; color:#000; }
...
$('.box').addClass('deco');
Ignoring the fact that having CSS styles living in JS code is evil (IMHO), I’m left wondering after all the years I’ve been doing this: which approach is more efficient? I’m working on task right now that will be doing a relatively massive amount of this type of style manipulation across multiple DOM elements, and in this case the performance is worth the consideration.
I did look around at other similar questions on SO but didn’t find an answer. Care to weigh in?
Thanks
The most efficient way to to have an existing class name in your CSS and just swap the class name.
See: Reflows & Repaints: CSS Performance making your JavaScript slow?