getElementsByClassName Method
In this tutorial, we will learn about the getElementsByClassName method in JavaScript.
In JavaScript, the getElementsByClassName() method is used to get a collection of elements with the specified class name from the document. It is a method of the document object that allows you to access and manipulate elements in the HTML document by their class name.
Syntax
The syntax for the getElementsByClassName() method is as follows:
let elements = document.getElementsByClassName(className);Where:
classNameis a string that specifies the class name of the element you want to get.elementsis a collection of elements with the specified class name.
Example
Suppose you have the following HTML document:
<!doctype html>
<html>
<head>
<title>Get Elements By Class Name Example</title>
</head>
<body>
<p class="red">This is a red paragraph.</p>
<p class="blue">This is a blue paragraph.</p>
<p class="red">This is another red paragraph.</p>
<script src="main.js"></script>
</body>
</html>You can use the getElementsByClassName() method to get all elements with the class name red and change their content:
let elements = document.getElementsByClassName("red");
elements.forEach(function (element) {
element.innerHTML = "This paragraph has been changed";
});This will change the content of all paragraphs with the class name red to "This paragraph has been changed".
Conclusion
- The
getElementsByClassName()method is used to get a collection of elements with the specified class name from the document. - It returns a collection of elements that match the specified class name.
- You can use the
getElementsByClassName()method to access and manipulate elements in the HTML document by their class name. - The
getElementsByClassName()method is supported in all modern browsers.
How is this guide?
Sign in to share your feedback
Help us improve by sharing your thoughts on this guide.
Last updated on