Welcome to %s forums

<No. 1 Community for developers, by developers/>

Login Register

How to add/remove class names from elements in javascript or es6 using classList?

Get support on JavaScript,jQuery, AJAX and other related technology.
Post Reply
admin
Site Admin
Posts: 45

How to add/remove class names from elements in javascript or es6 using classList?

Post by admin » Thu Aug 22, 2019 2:42 pm

Code: Select all

var el = document.getElementById("div1");

// Single class
el.classList.add("my-class");

// Multiple classes
el.classList.add("my-class", "another-class");

It has other methods also:
add– Adds a class to an element’s list of classes. If class already exists in the element’s list of classes, it will not add the class again.
remove– Removes a class from an element’s list of classes. If class does not exist in the element’s list of classes, it will not throw an error or exception.
toggle– Toggles the existence of a class in an element’s list of classes
contains– Checks if an element’s list of classes contains a specific class

Post Reply