Update the class for given div Using DOM manipulation

Question: How to update the class using vanilla javascript.

Answer:

Add class:

function addClass(selector, className) {

var elm = document.querySelector(selector);

if (elm){

elm.classList.add(className);

}

}

Remove class:

function addClass(selector, className){

var elm = document.querySelector(selector);

if (elm){

elm.classList.remove(className);

}

}
Toggle class:

function toggleClass(selector, className){

var elm = document.querySelector(selector);

if (elm){

elm.classList.toggle(className);

}

}

Check class:

function checkClass(selector, className){

var elm = document.querySelector(selector);

if (elm){

return elm.classList.contains(className);

}

}

Try it yourself: