How to find whether all element contains same class or not?

Overview

In web development, you often need to check if all elements share the same CSS class. This is useful for validation, styling consistency, or conditional logic. JavaScript provides the classList.contains() method combined with the Array.every() method to efficiently check if all selected elements contain a specific class.

Syntax

The basic syntax for checking if all elements contain the same class:

// Get elements and convert to array
let elements = Array.from(document.querySelectorAll('selector'));

// Check if all elements contain a specific class
let allHaveSameClass = elements.every(element => 
    element.classList.contains('className')
);

Method 1: Using classList.contains() with every()

This example demonstrates checking if all list items have the same class:

<!DOCTYPE html>
<html>
<head>
    <title>Check Same Class</title>
</head>
<body>
    <h3>Checking if all animals have the same class</h3>
    <ul>
        <li class="landAnimals">Cat</li>
        <li class="landAnimals">Dog</li>
        <li class="waterAnimals">Fish</li>
        <li class="landAnimals">Horse</li>
    </ul>
    <div id="result" style="border: 1px dashed black; padding: 10px; display: inline-block;"></div>
    
    <script>
        // Get all list items
        let animals = document.querySelectorAll("li");
        let animalArray = Array.from(animals);
        
        // Check if all elements have the "landAnimals" class
        const allLandAnimals = animalArray.every(li => {
            return li.classList.contains("landAnimals");
        });
        
        // Display result
        document.getElementById("result").innerHTML = 
            `All elements have 'landAnimals' class: ${allLandAnimals}`;
    </script>
</body>
</html>
All elements have 'landAnimals' class: false

Method 2: Checking Multiple Classes

You can also check if all elements contain any of multiple classes:

<!DOCTYPE html>
<html>
<head>
    <title>Check Multiple Classes</title>
</head>
<body>
    <div class="card primary">Card 1</div>
    <div class="card secondary">Card 2</div>
    <div class="card primary">Card 3</div>
    <div id="output"></div>
    
    <script>
        let cards = Array.from(document.querySelectorAll('div[class*="card"]'));
        
        // Check if all have 'card' class
        let allHaveCard = cards.every(card => card.classList.contains('card'));
        
        // Check if all have 'primary' class
        let allPrimary = cards.every(card => card.classList.contains('primary'));
        
        document.getElementById('output').innerHTML = `
            <p>All have 'card' class: ${allHaveCard}</p>
            <p>All have 'primary' class: ${allPrimary}</p>
        `;
    </script>
</body>
</html>
All have 'card' class: true
All have 'primary' class: false

Method 3: Function-Based Approach

Create a reusable function for class checking:

<!DOCTYPE html>
<html>
<head>
    <title>Reusable Function</title>
</head>
<body>
    <span class="highlight">Text 1</span>
    <span class="highlight">Text 2</span>
    <span class="normal">Text 3</span>
    <div id="functionResult"></div>
    
    <script>
        function allElementsHaveClass(selector, className) {
            let elements = Array.from(document.querySelectorAll(selector));
            if (elements.length === 0) return false;
            
            return elements.every(element => element.classList.contains(className));
        }
        
        // Test the function
        let spanResult = allElementsHaveClass('span', 'highlight');
        
        document.getElementById('functionResult').innerHTML = 
            `All spans have 'highlight' class: ${spanResult}`;
    </script>
</body>
</html>
All spans have 'highlight' class: false

How It Works

The solution uses two key JavaScript methods:

  • querySelectorAll(): Selects all elements matching the CSS selector
  • Array.every(): Tests whether all elements pass the condition (returns true only if ALL elements pass)
  • classList.contains(): Checks if an element has a specific CSS class

Comparison of Approaches

Method Use Case Returns
Basic every() + contains() Single class check Boolean
Multiple class checks Different classes on same elements Multiple booleans
Reusable function Repeated operations Boolean with error handling

Common Use Cases

  • Form validation - ensuring all required fields have error/success classes
  • UI consistency - checking if all buttons have the same styling class
  • Dynamic content filtering based on class presence
  • Conditional styling or behavior based on class uniformity

Conclusion

Using Array.every() combined with classList.contains() provides an efficient way to check if all elements share the same CSS class. This technique is essential for DOM validation, conditional styling, and maintaining UI consistency in dynamic web applications.

Updated on: 2026-03-15T23:19:01+05:30

579 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements