getElementsByClassName()

JavaScript DOM (Document Object Model) - getElementsByClassName() Tutorial

Table of Contents

  1. Introduction to the JavaScript DOM

  2. What is getElementsByClassName()?

  3. Syntax of getElementsByClassName()

  4. Accessing Elements by Class Name

  5. Practical Examples

    • Changing Text Content of Multiple Elements

    • Changing Styles of Multiple Elements

    • Iterating Over Elements with getElementsByClassName()

    • Adding Event Listeners to Multiple Elements

  6. Limitations of getElementsByClassName()

  7. Conclusion


1. Introduction to the JavaScript DOM

Welcome to the Codes with Pankaj tutorial on the JavaScript DOM (Document Object Model) and the getElementsByClassName() method! In this tutorial, we'll explore how to use JavaScript to access and manipulate HTML elements based on their class names using the getElementsByClassName() method. Let’s dive in!

The DOM is a representation of the structure of an HTML document. It allows JavaScript to interact with and manipulate the content of a webpage, making it dynamic and interactive.

2. What is getElementsByClassName()?

The getElementsByClassName() method is used to select and return a collection of all elements in the document that have a specific class name. This method is particularly useful when you want to apply changes to multiple elements at once.

Unlike getElementById(), which returns a single element, getElementsByClassName() returns an array-like collection of elements.

3. Syntax of getElementsByClassName()

document.getElementsByClassName(className);
  • className: The name of the class you want to select. This should be a string.

4. Accessing Elements by Class Name

The getElementsByClassName() method returns a live HTMLCollection of all elements that match the specified class name. This collection can be accessed like an array, using indices.

Example:

<!DOCTYPE html>
<html>
<head>
    <title>DOM Example</title>
</head>
<body>
    <h1 class="header">Header 1</h1>
    <h1 class="header">Header 2</h1>
    <p class="description">This is a paragraph.</p>
    <p class="description">This is another paragraph.</p>

    <script>
        let headers = document.getElementsByClassName("header");
        console.log(headers);  // Outputs a collection of <h1> elements with the class "header"
    </script>
</body>
</html>

5. Practical Examples

Changing Text Content of Multiple Elements

You can use getElementsByClassName() to access elements and change their text content.

Example:

let headers = document.getElementsByClassName("header");
for (let i = 0; i < headers.length; i++) {
    headers[i].textContent = "Updated Header " + (i + 1);
}

Changing Styles of Multiple Elements

You can also change the styles of all elements that share a class.

Example:

let descriptions = document.getElementsByClassName("description");
for (let i = 0; i < descriptions.length; i++) {
    descriptions[i].style.color = "blue";
    descriptions[i].style.fontWeight = "bold";
}

Iterating Over Elements with getElementsByClassName()

Since getElementsByClassName() returns a collection, you can iterate over the elements using a loop.

Example:

let descriptions = document.getElementsByClassName("description");
for (let i = 0; i < descriptions.length; i++) {
    console.log("Element " + i + ": " + descriptions[i].textContent);
}

Adding Event Listeners to Multiple Elements

You can use getElementsByClassName() to add event listeners to all elements with a specific class.

Example:

let headers = document.getElementsByClassName("header");
for (let i = 0; i < headers.length; i++) {
    headers[i].addEventListener("click", function() {
        alert("Header " + (i + 1) + " clicked!");
    });
}

6. Limitations of getElementsByClassName()

  • Live Collection: The HTMLCollection returned by getElementsByClassName() is live, meaning that it automatically updates if elements are added or removed from the DOM. This can lead to unexpected behavior if the DOM changes after you retrieve the collection.

  • No Direct Array Methods: Although getElementsByClassName() returns a collection similar to an array, it does not have array methods like forEach() or map(). You need to convert it to an array if you want to use these methods.

Example:

let headers = document.getElementsByClassName("header");
let headersArray = Array.from(headers);
headersArray.forEach(header => {
    header.style.color = "green";
});

7. Conclusion

In this detailed tutorial, we've explored the getElementsByClassName() method, which allows you to select and manipulate multiple elements based on their class names. By mastering this method, you can efficiently update and interact with groups of elements, making your web pages more dynamic and responsive.

For more tutorials and examples, visit www.codeswithpankaj.com! Happy coding!


Last updated