Tutorialsplane

Change Element class Using JavaScript


Change Element class Using JavaScript : You can use JavaScript to change the element’s class simply using the className attribute. You can also use this to add multiple classes to the element. Here in this tutorial we are going to explain how to change the element’s class using JavaScript. You can use our online editor to run the demo.


How to Change Element class Using JavaScript ?

JavaScript Replace(Change) All Classes By One(Single) Class

You can use className attribute to replace all classes by one class as below –

JavaScript className : Syntax

Syntax to change the className using the pure JavaScrpt is as Below –

JavaScript className Syntax:

document.getElementById("ElementId").className = "NewClass";

Where ElementId is id selector of the element. NewClass is class name you want to add.

JavaScript className : Example

JavaScript className Syntax:


Try it »

The above example changes the class of element which have id “myId”. It will add the new class YellowBg to the element. If you run the above example it will produce the output something like this –

Note : The above method will change all classes and add only the provided class ie. YelllowBg. All Classes will be replaced by the new class YellowBg

More Examples

Let’s have look over more example and demo here.


JavaScript Add Additional Class

If you want to add additional class in the existing element without removing/affecting the existing classes, use the className method as in below example –

JavaScript Append className : Example


Try it »

Note : Add a blank space before the class name eg – +” borderBlack”.

The above example will append the given class “borderBlack” to the element. Make sure you add a blank space before the class name so that it is not collapsed with other existing class name.