This post will discuss how to add a CSS class to an HTML element using JavaScript and jQuery.

1. Using JavaScript className property

The className property is commonly used to set the value of the class attribute of an element in plain JavaScript. The following code demonstrates this by setting the class attribute for the div element and replaces its existing classes, if any:

JS


CSS


HTML



Edit in JSFiddle

 
To add a class to an element rather than replacing its existing classes, use the += operator instead. Note, it is important to prefix the new classname with space; otherwise, one of the existing classes of an element is lost.

JS


CSS


HTML



Edit in JSFiddle

 
To apply multiple classes, specify the list of space-separated names of the classes for the className property.

JS


CSS


HTML



Edit in JSFiddle

2. Using JavaScript classList property

The classList property returns a collection of the class attributes of the element, which can be later modified using the add() and remove() methods. The add() method adds a class to the list.

JS


CSS


HTML



Edit in JSFiddle

 
To remove a class, you can use the element.classList.remove() method.

JS


CSS


HTML



Edit in JSFiddle

3. Using jQuery .addClass() method

If you’re on jQuery, you can use the .addClass() method to add the specified class to an element. It works by manipulating the class attribute of the element.

jQuery


CSS


HTML



Edit in JSFiddle

4. Using jQuery .css() method

Alternatively, you can use jQuery’s .css() for setting one or more CSS properties to an element. It works by modifying the value of the style property of the element.

jQuery


HTML



Edit in JSFiddle

 
Note that unless values of the CSS properties are dynamically generated, it’s recommended to use classes instead.

That’s all about adding a CSS class to an HTML element using JavaScript and jQuery.