Skip to content
Related Articles
Get the best out of our app
Open App

Related Articles

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

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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. 

  • Firstly, we need to select all those elements from the HTML document on which we want to check if they have the same CSS class or not using the document.querySelectorAll() method in JavaScript.
  • Since the querySelectorAll() method returns a node list of all the selected elements, we first need to convert this node list into an array using the Array.prototype.from() method so that we can call the every() method on it.
  • Finally, we will use the every() method on the returned array of the selected elements which would return true only if all the elements of the array have the specified class.

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">
    <meta charset="UTF-8" />
    <meta name="viewport" content=
        "width=device-width, initial-scale=1.0" />
      To find whether all element contains same class or not
    <div id="container">
        <button class="active">GeeksforGeeks</button>
        <button class="active">GeeksforGeeks</button>
        <button class="active">GeeksforGeeks</button>
        <button class="active">GeeksforGeeks</button>
        <button class="active">GeeksforGeeks</button>


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;


    // 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;

Output: Click here to check the live output.

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

My Personal Notes arrow_drop_up
Last Updated : 12 Jan, 2023
Like Article
Save Article
Similar Reads
Related Tutorials