Over a million developers have joined DZone.

Quick Tip – Change CSS Classes and Not Element Styles

· Web Dev Zone

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

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.

Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.


Published at DZone with permission of Gil Fink, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}