How do Add class using Javascript?


I wanted to add or remove classes from my HTML <div> dynamically using Javascript, I don't want to use jQuery here, so How can I add a class using JS?

If possible, I would also like to know how can I toggle class in Javascript


Asked by:- neena
0
: 112 At:- 9/26/2018 11:17:25 AM
Javascript js-add-class javascript-toggle-class






1 Answers
profileImage Answered by:- manish

Suppose this is your HTML and you want to add a class using javascript

<div id="MainDiv" class="ClassForDiv">
  
</div>

So here is the Javascript for it to add class for <div id="div1">

Add Class using Javascript

var nameElem = document.getElementById("MainDiv");
nameElem.classList.add("anyclss");

Toggle Class using Javascript

Every element has a classList property containing its class attributes. This property provides methods that make it straightforward to add or remove a class.

function toggleClass() {

 var myDivClasses = document.getElementById("MainDiv").classList;

 if (myDivClasses.contains("blue")) {
    myDivClasses.remove("blue");
 }else {
    myDivClasses.add("blue");
 }

}

An even simpler way to accomplish the same thing is to use the toggle() method. Which will add the provided class if it is not present, or remove it if it is:

function toggleColor() {

 document.getElementById("MainDiv").classList.toggle("blue");

}

here is the similar codepen example.

Removing class using Javascript

You can use classList.remove() method to remove a class

nameElem.classList.remove("anyclss")

Hope it helps.

2
At:- 9/26/2018 4:17:39 PM
Excellent answer, thank you for complete details. 0
By : neena - at :- 10/2/2018 8:17:24 AM





Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use

Subscribe Now

Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly