Quick Tip – Change CSS Classes and Not Element Styles

March 31, 2013

no comments

Quick Tip – Change CSS Classes and Not Element Styles

A few days ago I wrote a quick tip to ensure only one reflow when you need to manipulate the Document Object Model (DOM). Continuing that post, here is another JavaScript mistake I’m seeing from time to time and a way to go around it.

The Scenario

You need to change some element’s style as a response to some event. Here is a simple function that contains the problem:

function changeElementStyle(element) {
    element.style.color = '#fff';
    element.style.backgroundColor = '#000';
    element.style.width = "100px";
}

If you read my previous post, you know that every single DOM manipulation including style changes can trigger a reflow. In the previous code we have three potential reflows.

Suggested Solution

A way to solve the previous problem is using CSS classes instead of manipulating the element’s style. First, you will have to add a new class in your CSS file. Here is the previous style changes as a CSS class:

.changedstyle {
    color: #fff;
    background-color: #000;
    width: 100px;
}

Now change the previous function to the following function:

function changeElementStyle(element) {
    element.className = 'changedstyle';
}

Now we will have only one optional reflow instead of three and that is better.

Summary

When you are manipulating your DOM you should remember the Browser reflow process even if it is only simple style change. You can’t control when reflows occur but you can minimize their impact on your app performance.

Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>