The getElementsByClassName function is utilized to retrieve elements based on their class name attribute. This method of the Document Object Model (DOM) produces an array-like object containing all elements that bear the designated class name. When the getElementsByClassName method is invoked on a specific element, it searches throughout the entire document and returns solely those elements that correspond to the provided class name.
Syntax
var ele=document.getELementsByClassName('name');
In this context, the argument named 'name' is essential and must be provided. It is a string that indicates either a single class name or a list of class names that need to be matched.
Example of getElementsByClassName Method
Let us examine a few examples to gain insight into and comprehend the real-world application of the method.
Example
This is a straightforward class implementation that provides an array-like object when the variable x is called.
<html>
<head> <h5>DOM Methods </h5> </head>
<body>
<div class="Class">
This is a simple class implementation
</div>
<script type="text/javascript">
var x=document.getElementsByClassName('Class');
document.write("On calling x, it will return an arrsy-like object: <br>"+x);
</script>
</body>
</html>
Output:
In a like manner, we can develop the getElementsByClassName function to retrieve collections of elements associated with various classes.
Difference between getElementsByClassName, querySelector and querySelectorAll Methods
getElementsByClassName: This method identifies elements that possess the specified class name and returns a collection of these matched elements. The elements returned are a live HTML collection, which means that any modifications in the Document Object Model will be automatically reflected in this collection of live elements.
querySelector: This method retrieves only one element that corresponds to the given classname. In cases where no matching element is found, it will return null.
The key takeaway is that all the methods previously outlined yield either a single element or a collection of elements. However, the getElementsByClassName method facilitates dynamic updates, whereas the other two methods are intended for static use.