Skip to main content

getElementsByClassName in JavaScript DOM (Live Playground)

In this tutorial, we will learn how to use the getElementsByClassName method in JavaScript to select and manipulate HTML elements by their class attribute. We'll cover the basics of the method and provide sample code with explanations.

What is getElementsByClassName?

The getElementsByClassName method is a built-in JavaScript DOM method that allows you to select a collection of HTML elements by their class attribute. The method returns a live HTMLCollection of all elements with the specified class name, or an empty collection if no elements with the given class name are found. It enables you to access multiple elements with the same class and perform various operations, such as modifying content or applying styles.

Sample Code: Using getElementsByClassName

Let's say we have the following HTML document:

<!DOCTYPE html>
<html>
<head>
<title>getElementsByClassName Example</title>
</head>
<body>
<h1 class="mainHeading">Welcome to My Web Page!</h1>
<p class="mainParagraph">This is an introductory paragraph.</p>
<p class="mainParagraph">This is another paragraph with the same class.</p>
</body>
</html>

To use getElementsByClassName to select elements, you'll need to include a JavaScript <script> tag in your HTML document. For this example, we will add an inline script, although it's generally recommended to use external JavaScript files for larger projects.

Here's how you can select all p elements with the class mainParagraph and change their text content:

<!DOCTYPE html>
<html>
<head>
<title>getElementsByClassName Example</title>
</head>
<body>
<h1 class="mainHeading">Welcome to My Web Page!</h1>
<p class="mainParagraph">This is an introductory paragraph.</p>
<p class="mainParagraph">This is another paragraph with the same class.</p>

<script>
// Select all elements with the class "mainParagraph"
var mainParagraphs = document.getElementsByClassName('mainParagraph');

// Loop through the collection and change the text content of each element
for (var i = 0; i < mainParagraphs.length; i++) {
mainParagraphs[i].textContent = 'This paragraph has been updated.';
}
</script>
</body>
</html>

After running this code, the text content of all p elements with the class mainParagraph will be updated to "This paragraph has been updated.".

Live Playground, Try it Yourself

Conclusion

The getElementsByClassName method is a powerful way to select and manipulate HTML elements by their class attribute. By mastering this method, you can easily access and modify multiple elements with the same class in your HTML documents, allowing you to create dynamic and interactive web pages.