0

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

4 Answers 4

1

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?

Sign up to request clarification or add additional context in comments.

1 Comment

Although I would agree with you do you have any supporting links. Assuming efficient means quicker, do modern browsers process class changes faster than inline? A class is much cleaner and easier to deal with but I'd be interested in seeing some metrics if you know of any.
1

Run a benchmark on jsperf.com and find out the most efficient method yourself. You could also share your findings here for posterity.

Comments

1

In plain javascript changing className is normally faster than changing element.style, at least according to testing done by quirksmode.

How jQuery does in the same test is uncertain, as there are quite a few additional checks both when changing styles and classes in jQ, but I would tend to think it's about the same result.

All in all if changing more than a few styles on an element, classes will generally be faster, or about the same speed as styles, and since classes is much cleaner and easier to work with, I'd go for that, unless you're just changing one or two simple CSS rules.

Comments

0

you are already right bro !, we can use a combination of jQuery and external CSS to elicit the same effect. more efficient than the first one, however it also depends upon the situation...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.