Open In App

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

Problem statement: Given an HTML document with many elements, we have to find if all the selected elements contain the same particular CSS class or not. This problem can be easily accomplished with the help of JavaScript.

Approach: For this problem, we will be using Array.prototype.every() method available on the array object in JavaScript. This method returns true only if all the elements of the array (on which the method is called) satisfy a given condition. 



Example:  In the following example, we have six-button elements in the HTML document, out of which only five have the “active” CSS class added to them. 




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content=
        "width=device-width, initial-scale=1.0" />
    <title>
      To find whether all element contains same class or not
    </title>
</head>
  
<body>
    <div id="container">
        <button class="active">GeeksforGeeks</button>
        <button class="active">GeeksforGeeks</button>
        <button class="active">GeeksforGeeks</button>
        <button>GeeksforGeeks</button>
        <button class="active">GeeksforGeeks</button>
        <button class="active">GeeksforGeeks</button>
        <h1></h1>
    </div>
</body>
</html>




button {
    background-color: black;
    color: white;
    padding: 10px 24px;
    width: 300px;
    font-size: 18px;
    border: none;
    font-weight: bold;
    transition: all 0.4s;
    margin: 24px 80px;
}
  
#container {
    display: flex;
    flex-direction: column;
}
  
h1 {
    margin: 24px 80px;
}
  
.active {
    background-color: green;
}




<script>
    // Select the required elements
    let buttons = document.querySelectorAll("button");
    let text = document.querySelector("h1");
      
    // Convert the returned node list into an array
    buttons = Array.from(buttons);
      
    // Check if all the selected elements have
    // the class using every() method
    let check = buttons.every((btn) 
        => btn.classList.contains("active"));
    text.textContent = check;
</script>

Output: Click here to check the live output.



If you add the “active” CSS class to all the buttons, the following output is shown.


Article Tags :