HTML Document getElementsByClassName() Method: Getting Elements by Class Name

The getElementsByClassName() method of the HTML Document object is a fundamental tool in JavaScript for selecting HTML elements based on their class name. It returns a live HTMLCollection of all elements in the document that have the specified class name. This guide will provide a comprehensive overview of the getElementsByClassName() method, including its syntax, usage, practical examples, and best practices.

What is getElementsByClassName()?

The getElementsByClassName() method allows you to retrieve a collection of all elements within an HTML document that share a specific class name. This is particularly useful for manipulating multiple elements with a common styling or behavior.

Purpose of getElementsByClassName()

The primary purpose of getElementsByClassName() is to:

  • Select multiple HTML elements that share a specific class name.
  • Retrieve a live HTMLCollection of these elements.
  • Enable manipulation of these elements, such as changing their content, style, or attributes.

Syntax

The syntax for the getElementsByClassName() method is straightforward:

const elements = document.getElementsByClassName(className);

Where:

  • elements: A live HTMLCollection of elements with the specified class name.
  • className: A string representing the class name to search for.

Parameters

The getElementsByClassName() method accepts a single parameter:

Parameter Type Description
`className` String The class name to search for. Multiple class names can be specified, separated by spaces.

Return Value

The getElementsByClassName() method returns:

  • An HTMLCollection object containing all elements in the document that have the specified class name(s).
  • An empty HTMLCollection if no elements with the specified class name(s) are found.

Basic Usage

Let’s start with a basic example to illustrate how to use the getElementsByClassName() method.

<!DOCTYPE html>
<html>
<head>
    <title>getElementsByClassName Example</title>
</head>
<body>
    <div class="myClass">Element 1</div>
    <div class="myClass">Element 2</div>
    <div class="anotherClass">Element 3</div>

    <script>
        const elements_basic = document.getElementsByClassName("myClass");
        for (let i = 0; i < elements_basic.length; i++) {
            elements_basic[i].textContent = "Updated Element";
        }
    </script>
</body>
</html>

Output:

Element 1: Updated Element
Element 2: Updated Element
Element 3: Element 3

In this example, all elements with the class name "myClass" are selected and their text content is updated.

Selecting Multiple Class Names

You can specify multiple class names separated by spaces to select elements that have all the specified classes.

<!DOCTYPE html>
<html>
<head>
    <title>getElementsByClassName Multiple Classes Example</title>
</head>
<body>
    <div class="class1 class2">Element 1</div>
    <div class="class1">Element 2</div>
    <div class="class2">Element 3</div>

    <script>
        const elements_multiple = document.getElementsByClassName("class1 class2");
        for (let i = 0; i < elements_multiple.length; i++) {
            elements_multiple[i].textContent = "Selected Element";
        }
    </script>
</body>
</html>

Output:

Element 1: Selected Element
Element 2: Element 2
Element 3: Element 3

Here, only the element with both "class1" and "class2" is selected and updated.

Using getElementsByClassName() within an Element

You can also use getElementsByClassName() on a specific element, rather than the entire document, to search for elements with a class name within that element.

<!DOCTYPE html>
<html>
<head>
    <title>getElementsByClassName Within Element Example</title>
</head>
<body>
    <div id="myContainer">
        <div class="nestedClass">Element 1</div>
        <div class="nestedClass">Element 2</div>
    </div>
    <div class="nestedClass">Element 3</div>

    <script>
        const container_element = document.getElementById("myContainer");
        const elements_within = container_element.getElementsByClassName("nestedClass");
        for (let i = 0; i < elements_within.length; i++) {
            elements_within[i].textContent = "Updated Nested Element";
        }
    </script>
</body>
</html>

Output:

Element 1: Updated Nested Element
Element 2: Updated Nested Element
Element 3: Element 3

In this case, only the elements with the class name "nestedClass" inside the div with the ID "myContainer" are selected and updated.

Live HTMLCollection

One important characteristic of getElementsByClassName() is that it returns a live HTMLCollection. This means that the collection is automatically updated when elements are added or removed from the document that match the specified class name.

<!DOCTYPE html>
<html>
<head>
    <title>Live HTMLCollection Example</title>
</head>
<body>
    <div class="dynamicClass">Element 1</div>

    <button onclick="addElement()">Add Element</button>

    <script>
        const elements_live = document.getElementsByClassName("dynamicClass");

        function addElement() {
            const newElement = document.createElement("div");
            newElement.className = "dynamicClass";
            newElement.textContent = "New Element";
            document.body.appendChild(newElement);

            // The HTMLCollection is automatically updated
            console.log("Number of elements with class 'dynamicClass': " + elements_live.length);
        }
    </script>
</body>
</html>

Each time you click the “Add Element” button, a new element with the class "dynamicClass" is added to the document, and the HTMLCollection is automatically updated.

Practical Examples

Example 1: Styling Elements with a Specific Class

You can use getElementsByClassName() to apply styles to elements with a specific class name.

<!DOCTYPE html>
<html>
<head>
    <title>Styling Elements Example</title>
    <style>
        .highlighted {
            color: red;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <div>Normal Element</div>
    <div class="highlighted">Highlighted Element</div>
    <div>Another Normal Element</div>
    <div class="highlighted">Another Highlighted Element</div>

    <script>
        const elements_style = document.getElementsByClassName("highlighted");
        for (let i = 0; i < elements_style.length; i++) {
            elements_style[i].style.fontSize = "20px";
        }
    </script>
</body>
</html>

In this example, the elements with the class "highlighted" are styled with a larger font size using JavaScript.

Example 2: Toggling Visibility of Elements

You can use getElementsByClassName() to toggle the visibility of elements with a specific class name.

<!DOCTYPE html>
<html>
<head>
    <title>Toggling Visibility Example</title>
    <style>
        .hidden {
            display: none;
        }
    </style>
</head>
<body>
    <div class="toggleable">Element 1</div>
    <div class="toggleable hidden">Element 2</div>

    <button onclick="toggleElements()">Toggle Elements</button>

    <script>
        const elements_toggle = document.getElementsByClassName("toggleable");

        function toggleElements() {
            for (let i = 0; i < elements_toggle.length; i++) {
                if (elements_toggle[i].classList.contains("hidden")) {
                    elements_toggle[i].classList.remove("hidden");
                } else {
                    elements_toggle[i].classList.add("hidden");
                }
            }
        }
    </script>
</body>
</html>

Clicking the “Toggle Elements” button will toggle the visibility of elements with the class "toggleable".

Best Practices

  • Use Specific Class Names: Use descriptive and specific class names to avoid unintended selection of elements.
  • Consider Performance: While getElementsByClassName() is generally efficient, excessive use in performance-critical code may impact performance. Consider alternative selection methods if necessary.
  • Understand Live Collections: Be aware that HTMLCollection is live, and changes to the DOM will be reflected in the collection.
  • Use classList for Class Manipulation: Use the classList property for adding, removing, and toggling classes on elements.

Alternatives

While getElementsByClassName() is useful, there are alternative methods for selecting elements in JavaScript:

  • querySelector() and querySelectorAll(): These methods use CSS selectors to select elements and provide more flexibility in selecting elements based on various criteria.
  • getElementById(): This method selects a single element by its ID, which is more efficient if you need to select a specific element.
  • getElementsByTagName(): This method selects elements by their tag name.

Browser Support

The getElementsByClassName() method is widely supported across all modern web browsers.

Conclusion

The getElementsByClassName() method is a valuable tool for selecting HTML elements based on their class names. Understanding its syntax, usage, and live HTMLCollection behavior will enable you to effectively manipulate elements in your web applications. By following the best practices and considering the alternatives, you can optimize your code for performance and maintainability.