ZetCode

JavaScript classList.contains

last modified April 2, 2025

In this article, we explore the classList.contains method in JavaScript. This method is essential for checking CSS class presence on DOM elements, enabling dynamic styling and behavior in web applications.

Basic Definition

The classList.contains method checks if an element's class list contains a specified CSS class. It returns true if the class exists and false if it doesn't.

This method is part of the DOMTokenList interface provided by the classList property. It's widely used for conditional styling and state management in modern web applications.

Basic classList.contains

This example demonstrates how to check if an element has a specific CSS class.

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Basic classList.contains</title>
    <style>
        .highlight {
            background-color: yellow;
        }
    </style>
</head>
<body>

<div id="content" class="highlight">Sample content</div>

<script>
    const element = document.getElementById('content');
    const hasClass = element.classList.contains('highlight');
    console.log(hasClass); // Output: true
</script>

</body>
</html>

In this basic example, we have a div element with the class "highlight". The JavaScript code checks for this class using classList.contains.

The method returns true because the element has the specified class. This demonstrates the fundamental usage of classList.contains.

Conditional Styling

This example shows how to apply styles conditionally based on class presence.

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Conditional Styling</title>
    <style>
        .active {
            color: green;
            font-weight: bold;
        }
    </style>
</head>
<body>

<p id="status">Account Status: Normal</p>
<button onclick="toggleStatus()">Toggle Status</button>

<script>
    function toggleStatus() {
        const status = document.getElementById('status');
        if (status.classList.contains('active')) {
            status.textContent = 'Account Status: Normal';
            status.classList.remove('active');
        } else {
            status.textContent = 'Account Status: Active';
            status.classList.add('active');
        }
    }
</script>

</body>
</html>

Here we have a paragraph showing account status and a toggle button. The toggleStatus function checks for the 'active' class using classList.contains.

Depending on the result, it updates the text and toggles the class. This demonstrates practical use of classList.contains for UI state.

Form Validation Feedback

This example demonstrates using classList.contains for form validation feedback.

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Form Validation</title>
    <style>
        .error {
            border: 2px solid red;
        }
        .error-message {
            color: red;
            display: none;
        }
        .show {
            display: block;
        }
    </style>
</head>
<body>

<input type="text" id="username" placeholder="Username">
<div id="usernameError" class="error-message">Username is required</div>
<button onclick="validateForm()">Submit</button>

<script>
    function validateForm() {
        const input = document.getElementById('username');
        const error = document.getElementById('usernameError');
        
        if (input.value.trim() === '') {
            input.classList.add('error');
            error.classList.add('show');
        } else {
            input.classList.remove('error');
            error.classList.remove('show');
        }
    }
</script>

</body>
</html>

In this form validation example, we check input values and provide visual feedback. While not directly using contains, it shows the context.

The example demonstrates how class manipulation (add/remove) works with classList, which often pairs with contains checks.

Toggle Navigation Menu

This example shows how to use classList.contains for a responsive navigation menu.

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Navigation Menu</title>
    <style>
        nav {
            background: #333;
            padding: 1rem;
        }
        .nav-links {
            display: flex;
            list-style: none;
        }
        .nav-links li {
            margin-right: 1rem;
        }
        .mobile-menu {
            display: none;
        }
        .show-menu {
            display: flex;
            flex-direction: column;
        }
    </style>
</head>
<body>

<button id="menuToggle">Toggle Menu</button>
<nav id="mainNav">
    <ul class="nav-links">
        <li>Home</li>
        <li>About</li>
        <li>Contact</li>
    </ul>
</nav>

<script>
    const toggle = document.getElementById('menuToggle');
    const nav = document.getElementById('mainNav');
    
    toggle.addEventListener('click', function() {
        if (nav.classList.contains('mobile-menu')) {
            nav.classList.remove('mobile-menu');
        } else {
            nav.classList.add('mobile-menu');
        }
    });
</script>

</body>
</html>

This navigation example toggles between mobile and desktop views. The classList.contains check determines the current state.

Based on the check, it either adds or removes the mobile menu class. This pattern is common in responsive design implementations.

Accordion Component

This example creates an accordion component using classList.contains for state.

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Accordion</title>
    <style>
        .accordion-item {
            border: 1px solid #ddd;
            margin-bottom: 5px;
        }
        .accordion-header {
            padding: 10px;
            background: #f5f5f5;
            cursor: pointer;
        }
        .accordion-content {
            padding: 0 10px;
            max-height: 0;
            overflow: hidden;
            transition: max-height 0.3s ease;
        }
        .accordion-item.active .accordion-content {
            max-height: 200px;
            padding: 10px;
        }
    </style>
</head>
<body>

<div class="accordion-item">
    <div class="accordion-header">Section 1</div>
    <div class="accordion-content">
        Content for section 1 goes here.
    </div>
</div>

<div class="accordion-item">
    <div class="accordion-header">Section 2</div>
    <div class="accordion-content">
        Content for section 2 goes here.
    </div>
</div>

<script>
    const headers = document.querySelectorAll('.accordion-header');
    
    headers.forEach(header => {
        header.addEventListener('click', function() {
            const item = this.parentElement;
            const isActive = item.classList.contains('active');
            
            // Close all items first
            document.querySelectorAll('.accordion-item').forEach(el => {
                el.classList.remove('active');
            });
            
            // Open current if it wasn't active
            if (!isActive) {
                item.classList.add('active');
            }
        });
    });
</script>

</body>
</html>

This accordion example uses classList.contains to check if an item is active before toggling its state. It demonstrates component state management.

The code first closes all items, then opens the clicked one if it wasn't already active. This creates the standard accordion behavior.

Source

MDN classList.contains Documentation

In this article, we have shown how to use classList.contains in JavaScript. This method is fundamental for class-based DOM manipulation in modern web development.

Author

My name is Jan Bodnar, and I am a passionate programmer with extensive programming experience. I have been writing programming articles since 2007. To date, I have authored over 1,400 articles and 8 e-books. I possess more than ten years of experience in teaching programming.

List all JS DOM tutorials.