Last Updated : Jan 1, 2023
The getElementsByClassName method returns all elements in a document that have the same class name. All elements with the same class name are returned as array-like objects by this function.
There are two ways to call the method:
- When a method is called on the complete document, it chooses all of the items in the document that have the same class name. document.getElementsByClassName('class-name') is an example.
- When the method is used on an element (parent), it selects just the elements in the element that have the same class name (parent). parent.getElementsByClassName('class-name') as an example. getElementsByClassName, not getElementByClassName, is the name of the method. Because a webpage may contain more than one element with the same class name, elements are used.
- To begin, type <! DOCTYPE html> to inform the web browser that the file is in HTML format.
- The <html> element, on the other hand, is used to signal the start of HTML content.
- The <head> tag now contains the information about web pages. The< title> element is used in this tag to provide a web page title. For example, the <head> and <title> tags are paired tags. As a result, both have the </head> and </title> closing tags.
- The classNames option is a string that indicates a class name or a list of comma-separated class names to match in the example above.
- The preceding example shows how to use the getElementsByClassName() function to pick the< li> items that are descendants of the <ul> element using the getElementsByClassName() method.
- The </body> and </html> tags, respectively, are used to close the body and html tags.
The getElementsByClassName() returns a collection of all HTML elements with matching class names in an array.