In this section, we will learn what the Element getElementsByTagName() method is and how to use it in JavaScript.
What is Element getElementsByTagName() Method in JavaScript?
The JavaScript Element getElementsByTagName() method is used to find those elements in an HTML document that first, are the descendants of the element that invoked this method and second, match the specified tag name that is set as the argument of this method.
For example, if we want to find those elements in a <body> element that are <li>, we could use this method as:
bodyElement.getElementsByTagName(“li”);
Note: here the bodyElement is a reference to the <body> tag in the document. Now with this statement, those <li> elements in the document that are the descendants of the <body> element will be returned as the items in a collection object.
Element getElementsByTagName() Method Syntax:
element.getElementsByTagName(“tag-name”);
Element getElementsByTagName() Method Parameter
The method takes one argument and that is the name of the tag we’re looking for.
Element getElementsByTagName() Method Return Value
The return value of this method is a collection object and each of its items is a reference to an element that matched the requirements of the method.
Example: document getElementsByTagName() method
See the Pen document getElementsByTagName() method by Omid Dehghan (@odchan1) on CodePen.