How To Add, Remove, Toggle Class Of A DOM Element In JavaScript

ExploreEXPLORE THE CATALOGSupercharge your career with 700+ hands-on coursesView All CoursesPythonJavaJavaScriptCReactDockerVue JSRWeb DevDevOpsAWSC#LEARNING TOOLSExplore the industry's most complete learning platformCoursesLevel up your skillsSkill PathsAchieve learning goalsProjectsBuild real-world applicationsMock InterviewsNewAI-Powered interviewsPersonalized PathsGet the right resources for your goalsLEARN TO CODECheck out our beginner friendly courses.PricingFor BusinessResourcesNewsletterCurated insights on AI, Cloud & System DesignBlogFor developers, By developersFree CheatsheetsDownload handy guides for tech topicsAnswersTrusted answers to developer questionsGamesSharpen your skills with daily challengesSearchCoursesLog InJoin for freeHow to add, remove, toggle class of a DOM element in JavaScript

With the classList property of a DOM element, we can add, remove, check, and toggle an element’s class in JavaScript.

Print the classes of a DOM element

The classList property of a DOM element returns a DOMTokenList, which contains all the classes of the element.

Take a look at the code below:

OutputJavaScriptHTMLRunConsoleClear

Add class to an element

We can use the add method to add classes to the element. This is shown below:

OutputJavaScriptHTMLRunConsoleClear

The classList contains live data, meaning it will automatically update the class when a class is added or removed:

OutputJavaScriptHTMLRunConsoleClear

Remove the class of an element

We can use the remove method to remove classes from an element. Take a look at the following code:

OutputJavaScriptHTMLRunConsoleClear

Check if a DOM element contains a certain class

To check if there is a class present in a DOM element, we can use the contains method, as shown below:

OutputJavaScriptHTMLRunConsoleClear

Toggle a class

To toggle a class, we can use the toggle method. The toggle method will:

  • Add the class if the class is not present in the element.
  • Remove the class if the class is present in the element.

The toggle method returns true if the class is added, and false if the class is removed.

OutputJavaScriptHTMLRunConsoleClear

Replace a class

To replace an existing class, we can use the replace method. The replace method returns true if the class was successfully replaced; otherwise, it returns false.

OutputJavaScriptHTMLRunConsoleClear

Relevant Answers

Explore Courses

Free Resources

License: Creative Commons-Attribution-ShareAlike 4.0 (CC-BY-SA 4.0)

Tag » Add Class To Dom Element Js