How to Select Multiple Elements by Class Name in JavaScript

In JavaScript, selecting multiple elements with the same class name is a common task when working with the DOM (Document Object Model). This is useful when you want to apply the same action to several elements at once. JavaScript provides a method called document.getElementsByClassName() to achieve this. In this post, we'll explore how to select multiple elements by their class name and perform actions on them.

Table of Contents

  1. Using document.getElementsByClassName()
  2. Looping Over the Selected Elements
  3. Using document.querySelectorAll()
  4. Conclusion

1. Using document.getElementsByClassName()

The document.getElementsByClassName() method allows you to select all elements that share the same class name. It returns a live HTMLCollection (similar to an array) of all matching elements.

Example:

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Select Elements by Class Name</title>
</head>
<body>
  <p class="info">This is the first paragraph.</p>
  <p class="info">This is the second paragraph.</p>
  <p>This paragraph doesn't have the class 'info'.</p>
  <script src="script.js"></script>
</body>
</html>

JavaScript (script.js):

const infoElements = document.getElementsByClassName("info");
console.log(infoElements);

Output:

HTMLCollection(2) [p.info, p.info]

Explanation:

  • document.getElementsByClassName("info") selects all <p> elements with the class name "info" and returns them in an HTMLCollection.
  • The result is an array-like collection containing the matching elements.

2. Looping Over the Selected Elements

After selecting multiple elements, you often need to perform some actions on them. Since document.getElementsByClassName() returns an HTMLCollection, you can loop through it using a for loop or the Array.from() method to convert it to an array.

Example: Changing Text Content

const infoElements = document.getElementsByClassName("info");

for (let i = 0; i < infoElements.length; i++) {
  infoElements[i].textContent = `This is paragraph ${i + 1}`;
}

Output in the HTML:

<p class="info">This is paragraph 1</p>
<p class="info">This is paragraph 2</p>

Explanation:

  • The loop iterates over each element in the infoElements collection and updates its textContent to reflect its position.

Example: Changing the Style

const infoElements = document.getElementsByClassName("info");

for (let element of infoElements) {
  element.style.color = "blue";
  element.style.fontWeight = "bold";
}

This changes the text color of all elements with the "info" class to blue and makes the text bold.

3. Using document.querySelectorAll()

Another way to select multiple elements by class name is to use document.querySelectorAll(). This method returns a NodeList, which is static (doesn’t update automatically when the DOM changes) and can be iterated over more easily with modern JavaScript features like forEach().

Example:

const infoElements = document.querySelectorAll(".info");

infoElements.forEach((element, index) => {
  element.textContent = `This is paragraph ${index + 1}`;
});

Output:

<p class="info">This is paragraph 1</p>
<p class="info">This is paragraph 2</p>

Explanation:

  • document.querySelectorAll(".info") selects all elements with the "info" class and returns a NodeList.
  • You can use the forEach() method to loop through the selected elements and modify them.

Difference Between getElementsByClassName() and querySelectorAll():

  • getElementsByClassName() returns a live HTMLCollection, meaning it updates automatically if the DOM changes.
  • querySelectorAll() returns a static NodeList, which does not update when the DOM changes, but allows more flexible iteration with methods like forEach().

Conclusion

To select multiple elements by their class name in JavaScript, you can use either document.getElementsByClassName() or document.querySelectorAll(), depending on your needs. Both methods allow you to retrieve all elements with the same class and perform actions on them, but querySelectorAll() provides more flexibility when working with modern JavaScript methods like forEach().

Key Points:

  • document.getElementsByClassName() returns a live HTMLCollection of elements with the specified class.
  • document.querySelectorAll() returns a static NodeList, allowing easier iteration with forEach().
  • You can loop over the selected elements to modify their content, styles, or attributes.

Comments