JS getElementByClassName

The document.getElementsByClassName() method in JavaScript is used to select and manipulate elements based on their class names. Unlike document.getElementById(), which returns a single element, getElementsByClassName() returns a live HTMLCollection of elements that match the specified class names.

This method allows you to retrieve all elements with a specific class name or a set of class names. It is especially useful when dealing with multiple elements that share the same class.

Syntex:

var elements = document.getElementsByClassName('className');

className: The class name or names to match. You can specify multiple class names separated by spaces.

Here’s an example demonstrating how to use the document.getElementsByClassName() method to interact with multiple elements sharing the same class name.

Example:

<div>
  <p class="highlight">Way To Code technologies.</p>
  <p class="highlight">This is a development company.</p>
  <button onclick="highlightText()">CLICK ME</button>
</div>

  <script>
    function highlightText() {
      // Get all elements with class 'highlight'
      var elements = document.getElementsByClassName("highlight");

      // Loop through the elements and change their style
      for (var i = 0; i < elements.length; i++) {
        elements[i].style.fontWeight = "bold";
      }
    }
  </script>

Output:

Way To Code technologies.

This is a development company.

Difference between getElementsByClassName(), querySelector() and querySelectorAll() Methods

1. getElementsByClassName()

Purpose: Retrieves all elements with a specified class name.

Return Type: Live HTMLCollection.

Behavior:

    Returns a live collection of elements, meaning it automatically updates if the document changes.

    You can pass a single class name or multiple class names separated by spaces.

var elements = document.getElementsByClassName('example-class');

2. querySelector()

Purpose: Retrieves the first element that matches a specified CSS selector.

Return Type: Single Element or null if no match is found.

Behavior:

    Returns only the first element that matches the CSS selector.

    Does not return a live collection; it is static.

var element = document.querySelector('.example-class');

3. querySelectorAll()

Purpose: Retrieves all elements that match a specified CSS selector.

Return Type: Static NodeList.

Behavior:

    Returns a static NodeList of elements, not live.

    Useful for selecting multiple elements based on more complex CSS selectors.

var elements = document.querySelectorAll('.example-class');