Setting CSS Styles using JavaScript | kirupa.com

Setting CSS Styles using JavaScript

by kirupa | 22 August 2013

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.

Onwards.

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");
myElement.style.backgroundColor = "#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.

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. Before we go any further, if you don't care about really old browsers, skip the rest of this and go to the Using the classList API article where you will see the new and improved way to add and remove classes. For maximum browser support, read on.

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">
	<li>One</li>
	<li>Two</li>
	<li>Three</li>
	<li>Four</li>
	<li>Five</li>
	<li>Six</li>
</ul>

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">
	<li>One</li>
	<li>Two</li>
	<li>Three</li>
	<li>Four</li>
	<li>Five</li>
	<li>Six</li>
</ul>

What I am going to show you is how to this exact thing using JavaScript. The amount of code involved is much more than directly applying the style you saw earlier, but the effort is totally worth it. To add or remove classes from an element, you need the addClass and removeClass functions:

function addClass(element, classToAdd) {
	var currentClassValue = element.className;
	 
	if (currentClassValue.indexOf(classToAdd) == -1) {
		if ((currentClassValue == null) || (currentClassValue === "")) {
			element.className = classToAdd;
		} else {
			element.className += " " + classToAdd;
		}
	}
}
function removeClass(element, classToRemove) {
	var currentClassValue = element.className;
	if (currentClassValue == classToRemove) {
		element.className = "";
		return;
	}
	var classValues = currentClassValue.split(" ");
	var filteredList = [];
	for (var i = 0 ; i < classValues.length; i++) {
		if (classToRemove != classValues[i]) {
			filteredList.push(classValues[i]);
		}
	}
	element.className = filteredList.join(" ");
}

To actually use these functions in an example, all you need to do is call addClass or removeClass, pass in an argument for the element you want to affect, and pass in one more argument with the class name.

For example, the JavaScript for adding the disableMenu class value to our dropDown element would look as follows:

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

That's all there is to it. When this code executes, our dropDown element will proudly sport the disableMenu class value. To reinforce what is going on, below is an example of the addClass and removeClass functions at work (you can also view it in its own page):

Click on any of the three colored squares to change the color of the text and the background. All of this is done by adding and removing a few class values. To learn more about the addClass and removeClass functions (as well as this example), check out the page devoted entirely to it.

Conclusion

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 my removeClass function and helped me come up with the better one you see here.

Getting Help

If you have questions, need some assistance on this topic, or just want to chat - post in the comments below or drop by our friendly forums (where you have a lot more formatting options) and post your question. There are a lot of knowledgeable and witty people who would be happy to help you out

Share

Did you enjoy reading this and found it useful? If so, please share it with your friends:

If you didn't like it, I always like to hear how I can do better next time. Please feel free to contact me directly at kirupa[at]kirupa.com.

Cheers!

Click on Start or Continue Discussion to add your message.

Read-only Archive of Old comments

Please enable JavaScript to view the comments powered by Disqus. blog comments powered by

This is a companion discussion topic for the original entry at http://www.kirupa.com/html5/setting_css_styles_using_javascript.htm

What do you think would happen if you tried to use your addClass routine to add class ‘foo’ to an element that already had a class ‘foobar’?

Good catch! It wouldn’t work because of this line right here:

if (currentClassValue.indexOf(classToAdd) == -1) {

I’ll update the example shortly. I’ll also emphasize more strongly that everyone should use classList instead of doing this manually: http://www.kirupa.com/html5/using_the_classlist_api.htm

:smiley:

Hello.
Read this article and wonder if you could give me input on my problem:
I want woocommerce product list to “grow/expand” from the center and out proportionally. Right now when there is one product displaying it does so at the very right. My css knowledge does not seem to be enough here, it seems like javascript is needed. However I am new to this. Could you give me a hint how I could solve this problem?

Thank you so much in advance if you find time to answer me!

Do you have a link to an example page with your product list?