The getElementsByTagName() method in JavaScript is used to retrieve a live HTMLCollection of elements with a specified tag name within the current document or within a specified element. It allows you to select and access multiple elements based on their tag name.
Syntax:
element.getElementsByTagName(tagName)
Parameters:
tagName(required):- A string representing the name of the tag to search for. It can be any valid HTML tag name like
"div","p","input","a", etc.
- A string representing the name of the tag to search for. It can be any valid HTML tag name like
Return Value:
- An
HTMLCollectionobject representing a live collection of elements with the specified tag name. If no elements are found, an empty collection is returned.
getElementsByTagName Example
This is a paragraph
This is another paragraph
This is a standalone paragraph
Note:
- The
tagNameparameter is case-insensitive, meaning"p","P", and"P"will all match<p>elements. getElementsByTagName()returns a live collection, meaning changes to the DOM are reflected dynamically in the collection.- If you want to target a specific element within a parent element, you can call
getElementsByTagName()on the parent element.
Compatibility:
getElementsByTagName()is supported in all major browsers including Chrome, Firefox, Safari, Edge, and Internet Explorer.