Flat Preloader Icon

get element by tag name

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.

Return Value:

  • An HTMLCollection object representing a live collection of elements with the specified tag name. If no elements are found, an empty collection is returned.
  •  
				
					<!DOCTYPE html>
<html>
<head>
    <title>getElementsByTagName Example</title>
</head>
<body>
    <div>
<p>This is a paragraph</p>
<p>This is another paragraph</p>
    </div>
    <p>This is a standalone paragraph</p>

    <script>
// Get all <p> elements in the document
        let paragraphs =
        document.getElementsByTagName("p");
        console.log(paragraphs.length); 
        // Output: 3

// Loop through the collection of <p> elements
for (let i = 0; i < 
paragraphs.length; i++) {
 console.log(paragraphs[i].textContent);
        }
    </script>
</body>
</html>

				
			

Note:

  • The tagName parameter 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.