How to toggle between adding and removing a class name from an element with JavaScript?

JavaScript provides several methods to toggle class names on HTML elements. The most efficient approach is using the classList.toggle() method, which automatically adds a class if it doesn't exist or removes it if it does.

Using classList.toggle() Method

The toggle() method is the simplest way to switch between adding and removing a class:

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
        .highlight {
            background-color: #3498db;
            color: white;
            padding: 20px;
            border-radius: 5px;
            font-size: 18px;
            text-align: center;
            transition: all 0.3s ease;
        }
        
        .content {
            margin: 20px 0;
            padding: 15px;
            border: 2px solid #ddd;
            border-radius: 5px;
        }
        
        button {
            padding: 10px 20px;
            font-size: 16px;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <h1>Toggle Class Example</h1>
    <button onclick="toggleClass()">Toggle Highlight</button>
    
    <div id="contentDiv" class="content">
        This div will be highlighted when you click the button!
    </div>
    
    <script>
        function toggleClass() {
            const element = document.getElementById("contentDiv");
            element.classList.toggle("highlight");
        }
    </script>
</body>
</html>

Manual Toggle with contains() and add()/remove()

You can also manually check if a class exists and toggle it accordingly:

<!DOCTYPE html>
<html>
<head>
    <style>
        .active {
            background-color: #e74c3c;
            color: white;
            padding: 15px;
            border-radius: 8px;
        }
    </style>
</head>
<body>
    <button onclick="manualToggle()">Manual Toggle</button>
    <p id="textElement">Click to toggle styling</p>
    
    <script>
        function manualToggle() {
            const element = document.getElementById("textElement");
            
            if (element.classList.contains("active")) {
                element.classList.remove("active");
                console.log("Class removed");
            } else {
                element.classList.add("active");
                console.log("Class added");
            }
        }
    </script>
</body>
</html>

Toggle with Return Value

The toggle() method returns true if the class was added, false if removed:

<!DOCTYPE html>
<html>
<head>
    <style>
        .styled {
            background: linear-gradient(45deg, #9b59b6, #3498db);
            color: white;
            padding: 10px;
            margin: 10px 0;
        }
    </style>
</head>
<body>
    <button onclick="toggleWithFeedback()">Toggle with Feedback</button>
    <div id="statusDiv">Status: No styling applied</div>
    
    <script>
        function toggleWithFeedback() {
            const element = document.getElementById("statusDiv");
            const wasAdded = element.classList.toggle("styled");
            
            if (wasAdded) {
                console.log("Class was added");
            } else {
                element.textContent = "Status: No styling applied";
                console.log("Class was removed");
            }
        }
    </script>
</body>
</html>

Comparison of Methods

Method Code Length Returns Value Best Use Case
classList.toggle() Short Boolean Simple toggle operations
Manual contains/add/remove Longer None Complex conditional logic

Browser Compatibility

The classList.toggle() method is supported in all modern browsers including IE10+. For older browsers, you may need a polyfill or use the manual approach.

Conclusion

Use classList.toggle() for most class toggling scenarios as it's concise and efficient. The manual approach offers more control when you need custom logic during the toggle operation.

Updated on: 2026-03-15T23:18:59+05:30

266 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements