javascript change class name

Javascript Change Class Name

If you are working on a project that involves dynamically changing the style of HTML elements, then you must know how to change class names using Javascript. There are many ways to do this, let's explore some of them:

Method 1: Using the classList property


let element = document.querySelector('.old-class');
element.classList.remove('old-class');
element.classList.add('new-class');

In the above code, we first select the element we want to modify using querySelector(). Then we remove the old class name using remove() and add a new class name using add().

Method 2: Using the className property


let element = document.querySelector('.old-class');
element.className = 'new-class';

In this method, we select the element using querySelector() and then simply assign the new class name to the className property. Note that this method will replace all existing classes with the new one, so be careful while using it.

Method 3: Using classList.toggle()


let element = document.querySelector('.toggle-class');
element.classList.toggle('active');

If you want to toggle a class name, you can use the toggle() method. In the above code, we select the element and toggle the 'active' class name. If the class is already present, it will be removed, and if it is not present, it will be added.

These are some of the ways you can change class names using Javascript. Make sure to use the correct method depending on your requirements.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe