Add, Remove and Toggle Class from DOM elements
In jQuery, you can manage class names of an element using the addClass()
, removeClass()
and toggleClass()
functions. The equivalents in JavaScript are classList.add
, classList.remove
and classList.toggle
attributes.
Refer to the following code snippet to learn how to manage class names in an element and through jQuery and vanilla JavaScript:
// Add, remove, and toggle class using jQuery
$(".blog-post").addClass("popular");
$(".blog-post").removeClass("popular");
$(".blog-post").toggleClass("popular");
// Add, remove, and toggle class using vanilla JavaScript
let blogPost = document.querySelector(".blog-post");
blogPost.classList.add("popular");
blogPost.classList.remove("popular");
blogPost.classList.toggle("popular");