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 the importance of dynamically hiding elements, understand the concept of HTML classes, and learn different methods to select elements by class using JavaScript. We will then dive into the implementation details, providing step-by-step explanations and working code examples.

Selecting Elements by Class

Once we have a good grasp of HTML classes, we can move on to selecting elements by class using JavaScript. There are multiple methods available that allow us to target elements based on their assigned classes. In this section, we'll explore two commonly used methods: getElementsByClassName() and querySelectorAll().

Overview of JavaScript Methods for Selecting Elements by Class

When it comes to selecting elements by class in JavaScript, two primary methods come to mind: getElementsByClassName() and querySelectorAll(). Both methods allow us to retrieve a collection of elements that share a common class. Let's take a closer look at each method −

  • getElementsByClassName() The getElementsByClassName() method is a built-in JavaScript method that retrieves a collection of elements with a specific class name. It takes the class name as an argument and returns a live HTMLCollection object.

let elements = document.getElementsByClassName(className);
  • The getElementsByClassName() method is widely supported in all modern browsers and offers a straightforward way to select elements by class. However, it returns a live collection, meaning that any changes made to the DOM will be automatically reflected in the collection.

  • querySelectorAll() The querySelectorAll() method, on the other hand, provides a more flexible way to select elements using CSS selectors. It accepts a CSS selector as an argument and returns a static NodeList object.

let elements = document.querySelectorAll(selector);
  • With querySelectorAll(), you can use any CSS selector, including class selectors, to retrieve a collection of elements. This method is supported in all modern browsers and offers more advanced selection capabilities. However, the returned collection is static, meaning it won't update automatically when the DOM changes.

Using GetElementsByClassName() Method

The getElementsByClassName() method is straightforward to use. It accepts a single argument, the class name, and returns a live HTMLCollection containing all elements with that class. Here's an example −

<!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); // Outputs a live HTMLCollection
   </script>
</body>
</html>

In this example, the getElementsByClassName() method is used to select all elements with the class name "box". The returned HTMLCollection can then be manipulated or accessed for further processing.

Using QuerySelectorAll() Method

The querySelectorAll() method provides more flexibility in selecting elements by class, as it allows the use of CSS selectors. This method returns a static NodeList containing all elements that match the specified selector. Here's an example −

<!DOCTYPE html>
<html>
<head>
   <title>Using querySelectorAll()</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.querySelectorAll('.box');
      console.log(elements); // Outputs a static NodeList
   </script>
</body>
</html>

In this example, the querySelectorAll() method is used with the CSS class selector ".box" to select all elements with the class name "box". The returned NodeList can be iterated over or accessed using array-like indexing.

Pros and Cons of each Method

Both getElementsByClassName() and querySelectorAll() have their strengths and considerations. Here are some points to keep in mind when choosing between them −

  • getElementsByClassName() is well-supported and returns a live HTMLCollection, allowing automatic updates when the DOM changes. However, it lacks the flexibility of CSS selectors.

  • querySelectorAll() offers more advanced selection capabilities with CSS selectors and returns a static NodeList. It provides greater flexibility but doesn't automatically update when the DOM changes.

Hiding Elements by Class

There are different approaches we can take to achieve this, depending on the level of control and compatibility we require.

Using CSS to Hide Elements by Class

One simple and effective way to hide elements by class is by utilizing the CSS display property. The display property allows us to control the visibility of elements on a webpage. Here's how we can use CSS to hide elements by class −

  • Introduction to CSS display property

    The CSS display property specifies the rendering behavior of an element. By setting it to none, we can effectively hide elements. For example 

let elements = .hidden {
   display: none;
}
  • Applying "display: none" to hide elements

    To hide elements using the defined CSS class, simply apply the class to the desired elements. For instance 

<div class="box hidden">This element is hidden.

The element with the class "box" and "hidden" will be hidden on the webpage.

  • Setting up CSS classes for hiding elements

    To make the hiding process more modular and reusable, it's beneficial to define CSS classes specifically for hiding elements. For example 

.hidden {
   display: none;
}

.invisible {
   visibility: hidden;
}

By having separate classes for different hiding behaviors, we can easily apply the desired visibility style to elements based on our requirements.

Applying CSS Classes Dynamically using JavaScript

While using CSS classes to hide elements is a straightforward approach, we can enhance the interactivity and control by manipulating these classes dynamically using JavaScript.

  • Adding a CSS class to hide elements

    To hide elements dynamically using JavaScript, we can add the CSS class associated with hiding to the desired elements. Here's an example −

let element = document.getElementById("myElement");
element.classList.add("hidden");

In this example, the hidden class is added to the element with the ID "myElement," effectively hiding it.

  • Removing a CSS class to show elements

    To show hidden elements again, we can remove the CSS class from the elements using JavaScript. Here's an example −

let element = document.getElementById("myElement");
element.classList.remove("hidden");

This code removes the hidden class from the element with the ID "myElement," making it visible again.

  • Manipulating class names using JavaScript

    JavaScript provides various methods to manipulate class names on elements. For example −

    • classList.add("className")  Adds a class to an element's class list.

    • classList.remove("className")  Removes a class from an element's class list.

    • classList.toggle("className")  Toggles the presence of a class in an element's class list.

    • classList.contains("className")  Checks if an element has a specific class.

By utilizing these methods, we can dynamically add or remove the desired CSS classes to achieve hiding or showing effects on elements.

Example: Hiding Elements by Class using CSS and JavaScript

Let's put everything together and demonstrate an example of hiding elements by class using CSS and JavaScript.

<!DOCTYPE html>
<html>
<head>
   <title>Hiding Elements by Class</title>
   <style>
      .hidden {
      display: none;
      }
   </style>
</head>
<body>
   <div class="box">Visible Element</div>
   <div class="box hidden">Hidden Element</div>
   
   <button onclick="hideElements()">Hide Elements</button>
   <button onclick="showElements()">Show Elements</button>
   
   <script>
      function hideElements() {
         let elements = document.getElementsByClassName("box");
         for (let i = 0; i < elements.length; i++) {
         elements[i].classList.add("hidden");
         }
      }
   
      function showElements() {
         let elements = document.getElementsByClassName("box");
         for (let i = 0; i < elements.length; i++) {
            elements[i].classList.remove("hidden");
         }
      }
   </script>
</body>
</html>

In this example, we have two <div> elements with the class "box." One element is initially visible, while the other is hidden using the CSS class "hidden." The two buttons trigger JavaScript functions that dynamically add or remove the "hidden" class to show or hide the elements accordingly.

Considerations for Compatibility and Performance

When hiding elements by class using CSS and JavaScript, it's important to consider browser compatibility and performance implications.

  • Browser compatibility for CSS and JavaScript methods

    Ensure that the CSS properties and JavaScript methods used to hide elements are supported across different browsers. It's recommended to check browser compatibility tables or use appropriate polyfills or fallbacks if needed.

  • Performance implications of using different approaches

    Manipulating the visibility of elements dynamically can impact performance, especially when dealing with a large number of elements. It's important to optimize the code and consider alternative approaches, such as hiding container elements instead of individual elements, if possible.

  • Optimizing the hiding process for large sets of elements

    When working with a large number of elements, consider using more efficient DOM traversal methods, like querySelectorAll(), and cache the selected elements to avoid redundant DOM queries. Additionally, batch operations or utilizing virtual rendering techniques can help improve performance when dealing with extensive lists or tables.

Conclusion

When working with a large number of elements, consider using more efficient DOM traversal methods, like querySelectorAll(), and cache the selected elements to avoid redundant DOM queries. Additionally, batch operations or utilizing virtual rendering techniques can help improve performance when dealing with extensive lists or tables.

Updated on: 07-Aug-2023

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements