

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to toggle between adding and removing a class name from an element with JavaScript?
To toggle between adding and removing a class name from an element with JavaScript, the code is as follows −
Example
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1" /> <style> .newStyle { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; width: 100%; padding: 25px; background-color: rgb(147, 80, 255); color: white; font-size: 25px; box-sizing: border-box; text-align: center; } </style> </head> <body> <h1>Adding className with JavaScript Example</h1> <button class="btn">Click here</button> <h2>Click the above button to add className to below div</h2> <div id="sampleDiv"> This is a DIV element. </div> <script> document.querySelector(".btn").addEventListener("click", addClassName); function addClassName() { var element = document.getElementById("sampleDiv"); element.classList.toggle("newStyle"); } </script> </body> </html>
Output
The above code will produce the following output −
On clicking the “Click here” button −
- Related Questions & Answers
- How to remove a class name from an element with JavaScript?
- How to toggle between hiding and showing an element with JavaScript?
- How to add a class name to an element with JavaScript?
- Removing an element from an Array in Javascript
- How to toggle between a like/dislike button with CSS and JavaScript?
- How to toggle between password visibility with JavaScript?
- How to check if an element has a certain class name with jQuery?
- Removing an array element from a MongoDB collection
- Removing an element from a given position of the array in Javascript
- How to toggle text with JavaScript?
- Adding an element in an array using Javascript
- Removing an element from the end of the array in Javascript
- Removing an element from the start of the array in javascript
- Toggle hide class only on selected div with JavaScript?
- How to filter a DIV element based on its class name wth CSS and JavaScript?
Advertisements