Skip to content
the poor coder

javascript change class name

Poor Man
Published
Reading time
1 min read
On this page

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#

Text

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#

Text

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()#

Text

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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC