close

How can I add and remove an active class to an element in pure JavaScript

Hello Guys, How are you all? Hope You all Are Fine. Today we are going to learn How can I add and remove an active class to an element in pure JavaScript in javascript. So Here I am Explain to you all the possible methods here.

Without wasting your time, Let’s start This Article.

How can I add and remove an active class to an element in pure JavaScript ?

  1. How can I add and remove an active class to an element in pure JavaScript ?

    can I add and remove an active class to an element in pure JavaScript Below should help.
    //Remove all classes by ID document.getElementById("elementIdHere").className = ""; //If you wish to keep some classes on the element, use below document.getElementById("elementIdHere").className = "keepClass";

  2. How can I add and remove an active class to an element in pure JavaScript ?

    can I add and remove an active class to an element in pure JavaScript Below should help.
    //Remove all classes by ID document.getElementById("elementIdHere").className = ""; //If you wish to keep some classes on the element, use below document.getElementById("elementIdHere").className = "keepClass";

Method 1

I’d personally stick with the document.querySelector method. querySelector accepts a CSS like query, which we will use to find an active class on the page. If it exists (the if statement), remove it and apply the new class on the target.

Please be aware that using className = "" will result in all classes being removed. It would be more neat to use classList for everything.

Method 2

Below should help.

//Remove all classes by ID
document.getElementById("elementIdHere").className = "";
//If you wish to keep some classes on the element, use below
document.getElementById("elementIdHere").className = "keepClass";

Summery

It’s all About this article. Hope all method helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which method worked for you? Thank You.

Leave a Comment