How to Hide an HTML Element by Class using JavaScript?

When working with dynamic web pages, it's often necessary to hide certain HTML elements based on specific conditions or user interactions. One common approach is to assign classes to these elements and then dynamically hide them using JavaScript. This provides a flexible and efficient way to control the visibility of elements without modifying the HTML structure.

In this article, we will explore how to hide HTML elements by class using JavaScript. We'll discuss different methods to select elements by class and demonstrate practical techniques for hiding and showing elements dynamically.

Methods for Selecting Elements by Class

JavaScript provides two primary methods for selecting elements by class: getElementsByClassName() and querySelectorAll(). Both methods allow us to retrieve collections of elements that share a common class.

Using getElementsByClassName()

The getElementsByClassName() method retrieves a live HTMLCollection of elements with a specific class name. It takes the class name as an argument and automatically updates when the DOM changes.

<!DOCTYPE html>
<html>
<head>
    <title>Using getElementsByClassName()</title>
</head>
<body>
    <div class="box">Box 1</div>
    <div class="box">Box 2</div>
    <div class="box">Box 3</div>
    
    <script>
        let elements = document.getElementsByClassName('box');
        console.log(elements.length); // Output: 3
        console.log(elements[0].textContent); // Output: Box 1
    </script>
</body>
</html>
3
Box 1

Using querySelectorAll()

The querySelectorAll() method provides more flexibility by accepting CSS selectors as arguments. It returns a static NodeList that doesn't update automatically when the DOM changes.

<!DOCTYPE html>
<html>
<head>
    <title>Using querySelectorAll()</title>
</head>
<body>
    <div class="box">Box 1</div>
    <div class="box special">Box 2</div>
    <div class="box">Box 3</div>
    
    <script>
        let allBoxes = document.querySelectorAll('.box');
        let specialBoxes = document.querySelectorAll('.box.special');
        
        console.log(allBoxes.length); // Output: 3
        console.log(specialBoxes.length); // Output: 1
    </script>
</body>
</html>
3
1

Comparison of Methods

Method Collection Type Updates Automatically CSS Selector Support
getElementsByClassName() HTMLCollection Yes (Live) No
querySelectorAll() NodeList No (Static) Yes

Hiding Elements Using CSS Classes

The most efficient way to hide elements is by applying CSS classes that control visibility. Here are two common approaches:

.hidden {
    display: none; /* Completely removes element from layout */
}

.invisible {
    visibility: hidden; /* Hides element but keeps its space */
}

Dynamic Hiding with JavaScript

JavaScript's classList property provides methods to manipulate CSS classes dynamically:

  • classList.add("className") - Adds a class
  • classList.remove("className") - Removes a class
  • classList.toggle("className") - Toggles a class
  • classList.contains("className") - Checks if class exists

Complete Example: Hide/Show Elements by Class

<!DOCTYPE html>
<html>
<head>
    <title>Hide Elements by Class</title>
    <style>
        .box {
            padding: 10px;
            margin: 5px;
            background-color: lightblue;
            border: 1px solid blue;
        }
        .hidden {
            display: none;
        }
    </style>
</head>
<body>
    <div class="box">Box 1 - Visible</div>
    <div class="box">Box 2 - Visible</div>
    <div class="box hidden">Box 3 - Initially Hidden</div>
    
    <button onclick="hideAllBoxes()">Hide All Boxes</button>
    <button onclick="showAllBoxes()">Show All Boxes</button>
    <button onclick="toggleBoxes()">Toggle Boxes</button>
    
    <script>
        function hideAllBoxes() {
            let boxes = document.querySelectorAll('.box');
            boxes.forEach(box => box.classList.add('hidden'));
        }
        
        function showAllBoxes() {
            let boxes = document.querySelectorAll('.box');
            boxes.forEach(box => box.classList.remove('hidden'));
        }
        
        function toggleBoxes() {
            let boxes = document.querySelectorAll('.box');
            boxes.forEach(box => box.classList.toggle('hidden'));
        }
    </script>
</body>
</html>

Performance Considerations

When working with large numbers of elements, consider these optimization techniques:

  • Cache element selections: Store selected elements in variables to avoid repeated DOM queries
  • Use efficient selectors: querySelectorAll() is generally faster for complex selections
  • Batch operations: Apply changes to multiple elements in a single operation when possible
  • Consider container hiding: Hide parent containers instead of individual child elements

Browser Compatibility

Both getElementsByClassName() and querySelectorAll() are well-supported across all modern browsers. The classList API is also widely supported, making these techniques reliable for cross-browser implementations.

Conclusion

Hiding HTML elements by class using JavaScript is accomplished through CSS classes and the classList API. Use querySelectorAll() for flexibility with CSS selectors, and leverage classList.add(), classList.remove(), and classList.toggle() for dynamic visibility control.

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

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements