In this section, we will learn what the document getElementsByClassName() method is and how to use it in JavaScript.
What is document getElementsByClassName() Method in JavaScript?
The JavaScript document getElementsByClassName() method is a way of accessing elements in an HTML document using the value set for the class attribute.
For example, if there are multiple elements in an HTML document that have the class attribute with the value “light”, then calling this method and passing this value as its argument, will return a collection object that contains a reference to each element with this value set for its class attribute.
document getElementsByClassName() Method Syntax:
document.getElementsByClassName(class-name);
document getElementsByClassName() Method Parameters
The method takes one argument, and that is a value that might be set for the class attribute of one or more HTML elements in a document.
Note: if you want to look for more than just one class name using this method, put all the class names in the same pair of double-quotation mark and separate them using white-space.
For example: “classOne classTwo classN”
document getElementsByClassName() Method Return Value
The return value of this method is a reference to a collection object named HTMLCollection which it contains references to the entire elements in a page that has the same value set for their class attribute.
Example: using document getElementsByClassName() Method in JavaScript
See the Pen using document getElementsByClassName() Method in JavaScript by Omid Dehghan (@odchan1) on CodePen.
How does getElementsByClassName() method work in JavaScript?
Here, we’ve used the getElementsByClassName() method to access those elements in a page that have a class attribute with the value “body”. There’s only one element with this value set for its attribute and that is the <body> element.
After that, we’ve used a pair of brackets with the value 0 to get the first item from the returned collection object. Finally, at the end we’ve used the `style` and `backgroundColor` properties to change the background color to light-blue.
Example: document get element by class name
See the Pen document get element by class name by Omid Dehghan (@odchan1) on CodePen.