Setting CSS Styles Using JavaScript

by kirupa   |   filed under JavaScript 101

When it comes to styling some content, the most common way is by creating a style rule and have its selector target an element or elements. A style rule would look as follows:

.batman {
	width: 100px;
	height: 100px;
	background-color: #333;

An element that would be affected by this style rule could look like this:

<div class="batman"></div>

On any given web page, you'll see anywhere from just a few to many MANY style rules each beautifully stepping over each other to style everything that you see. This isn't the only approach you can use to style content using CSS, though. It wouldn't be HTML if there weren't multiple ways to accomplish the same task!

Ignoring inline styles, the other approach that you can use to introduce elements to the goodness that is CSS styling involves JavaScript. You can use JavaScript to directly set a style on an element, and you can also use JavaScript to add or remove class values on elements which will alter which style rules get applied.

In this tutorial, you're going to learn about both of these approaches.


OMG! A JavaScript Book Written by Kirupa?!!

To kick your JavaScript skills into outer space, everything you see here and more (with all its casual clarity!) is available in both paperback and digital editions.


Why Would You Set Styles Using JavaScript?

Before we go further it is probably useful to explain why you would ever want to use JavaScript to affect the style of an element in the first place. In the common cases where you use style rules or inline styles to affect how an element looks, the styling kicks in when the page is loaded. That's awesome, and that's probably what you want most of the time.

There are many cases, especially as your content gets more interactive, where you want styles to dynamically kick in based on user input, some code having run in the background, and more. In these sorts of scenarios, the CSS model involving style rules or inline styles won't help you. While pseudoselectors like hover provide some support, you are still greatly limited in what you can do.

The solution you will need to employ for all of them is one that involves JavaScript. JavaScript not only lets you style the element you are interacting with, more importantly, it allows you to style elements all over the page. This freedom is very powerful and goes well beyond CSS's limited ability to style content inside (or very close to) itself.

A Tale of Two Styling Approaches

Like I mentioned in the introduction, you have two ways to alter the style of an element using JavaScript. One way is by setting a CSS property directly on the element. The other way is by adding or removing class values from an element which may result in certain style rules getting applied or ignored. Let's look at both of these cases in greater detail.

Setting the Style Directly

Every HTML element that you access via JavaScript has a style object. This object allows you to specify a CSS property and set its value. For example, this is what setting the background color of an HTML element whose id value is superman looks like:

var myElement = document.querySelector("#superman"); = "#D93600";

To affect many elements, you can do something as follows:

var myElements = document.querySelectorAll(".bar");

for (var i = 0; i < myElements.length; i++) {
	myElements[i].style.opacity = 0;

In a nutshell, to style elements directly using JavaScript, the first step is to access the element. I am using the querySelector method to make that happen. The second step is just to find the CSS property you care about and give it a value. Remember, many values in CSS are actually strings. Also remember that many values require a unit of measurement like px or em or something like that to actually get recognized. Also remember...actually, I forgot.

Lastly, some CSS properties require a more complex value to be provided with a bunch of random text followed by the value you care about. One of the more popular ones in this bucket is the transform property. One approach for setting a complex value is to use good old fashioned string concatenation: = "translate3d(" + xPos + ", " + yPos + "px, 0)";

That can get really irritating, for keeping track of the quotation marks and so on is something tedious and error-prone. One less irritating solution is to use the string literal syntax: = `translate3d(${xPos}px, ${yPos}px, 0)`;

Notice how this approach allows you to still provide custom values while avoiding all of the string concatenation complexity.

Special Casing Some Names of CSS Properties

JavaScript is very picky about what makes up a valid property name. Most names in CSS would get JavaScript's seal of approval, so you can just use them straight-up from the carton. There are a few things to keep in mind, though.

To specify a CSS property in JavaScript that contains a dash, simply remove the dash. For example, background-color becomes backgroundColor, the border-radius property transforms into borderRadius, and so on.

Also, certain words in JavaScript are reserved and can't be used directly. One example of a CSS property that falls into this special category is float. In CSS it is a layout property. In JavaScript, it stands for something else. To use a property whose name is entirely reserved, prefix the property with css where float becomes cssFloat.


Adding and Removing Classes Using JavaScript

The second approach involves adding and removing class values that, in turn, change which style rules get applied. For example, let's say you have a style rule that looks as follows:

.disableMenu {
	display: none;

In HTML, you have a menu whose id is dropDown:

<ul id="dropDown">

Now, if we wanted to apply our .disableMenu style rule to this element, all you would need to do is add disableMenu as a class value to the dropDown element:

<ul class="disableMenu" id="dropDown">

To accomplish the same result using JavaScript, we are going to use the classList API. This API makes it dirt simple to add or remove class values from an HTML element. To add the disableMenu class name to our dropDown element, use the add method on the HTML element's classList property:

var theDropDown = document.querySelector("#dropDown");

To remove the the disableMenu class name, we can call the classList API's remove method:

var theDropDown = document.querySelector("#dropDown");

That's all there is to working with class values in JavaScript, but that isn't all there is to the classList API. If you are feeling especially bored, there is a whole lot more you can do with the classList API beyond just adding and remove class values. To see the classList API and all of its hobbies described in greater detail, go here.


So, there you have it - two perfectly fine JavaScript-based approaches you can use for styling your elements. Of these two choices, if you have the ability to modify your CSS, I would prefer you go style elements by adding and removing classes. The simple reason is that this approach is far more maintainable. It is much easier to add and remove style properties from a style rule in CSS as opposed to adding and removing lines of JavaScript.

Also, a huge thanks to Chris Whitcoe who found some pretty egregious errors in an earlier version of this article that included my removeClass function - a function that we shall no longer speak of.

If you have a question about this or any other topic, the easiest thing is to drop by our forums where a bunch of the friendliest people you'll ever run into will be happy to help you out!


Get cool tips, tricks, selfies, and more...personally hand-delivered to your inbox!

( View past issues for an idea of what you've been missing out on all this time! )



Serving you freshly baked content since 1998!

Killer hosting by (mt) mediatemple

Facebook Twitter Youtube Pinterest Instagram Github
new books - yay!!!