JavaScript: Add a CSS class to an element.

This is a tutorial on how to add a CSS class to a HTML element using JavaScript. This can be useful if you need to dynamically alter the appearance of an element.

The CSS class.

Firstly, let’s create a simple CSS class that we can later add to a HTML element:

In the snippet above, we created a CSS class called “newClass“. This class does three things:

  • It sets the color of the element’s text to red.
  • It sets the font weight to bold.
  • And it sets the font style to italic.

As you can see, it’s pretty simple stuff!

The HTML element.

Now, let’s create an example HTML element:

Above, we created a DIV with the ID “intro”. Note that this ID is extremely important as will allow us to reference the element using JavaScript.

Inside the DIV, we wrote some sample text.

Adding a CSS class to an element using JavaScript.

Now, let’s add the CSS class “newClass” to the DIV element “intro”. For the purpose of this example, I have added a delay using the setTimeout() method so that you can see the style changing:

If you run the JavaScript above, you will see that “newClass” is added to “intro” after five seconds.

It is important to note that the classList.add approach will not work in Internet Explorer version 9 and below.

If you do need to support older browsers, then you can use the following approach instead:

Here, we have directly modified the className property of the element. The only drawback to this approach is that it will overwrite any classes that were previously applied to the element.

Example:

will become:

Adding a CSS class using JQuery.

Luckily enough, the JQuery library has a method called addClass, which can be used to add CSS classes to an element. Let’s modify the example above to use JQuery instead of vanilla JavaScript:

The code snippet above should result in the following:

Change CSS class

JQuery’s .addClass() method works by manipulating the class attribute of the element.

“addClass is not working!”

If the examples above do not work for you, then I suggest that you check the following:

  1. Make sure that you are referencing the correct ID. i.e. If your element has the ID “header”, then you will need to reference it by that ID.
  2. Ensure that your CSS class has been defined. If this class was declared in an external stylesheet, then you will need to make sure that the stylesheet in question is being loaded.
  3. Make sure that the same ID hasn’t been used twice. Remember that the HTML ID attribute should act as a unique ID. Two elements with the same ID can cause problems.
  4. There is no need to reference the dot / period character when you are adding your CSS class. i.e. You should use addClass(“intro”), not addClass(“.intro”)

Hopefully, you found this tutorial to be useful!

Facebook Comments