Over a million developers have joined DZone.
Platinum Partner

Quick Tip – Change CSS Classes and Not Element Styles

· Web Dev Zone

The Web Dev Zone is brought to you in partnership with Mendix.  Discover how IT departments looking for ways to keep up with demand for business apps has caused a new breed of developers to surface - the Rapid Application Developer.

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.


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.

The Web Dev Zone is brought to you in partnership with Mendix.  Learn more about The Essentials of Digital Innovation and how it needs to be at the heart of every organization.


Published at DZone with permission of Gil Fink , DZone MVB .

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}