Over a million developers have joined DZone.

Quick Tip – Change CSS Classes and Not Element Styles

DZone's Guide to

Quick Tip – Change CSS Classes and Not Element Styles

· Web Dev Zone ·
Free Resource

Read this guide to learn everything you need to know about RPA, and how it can help you manage and automate your processes.

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.

Get the senior executive’s handbook of important trends, tips, and strategies to compete and win in the digital economy.


Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}