HTML Element getElementsByTagName() Method: Getting Child Elements by Tag Name

The getElementsByTagName() method is a powerful tool in the HTML DOM (Document Object Model) that allows you to retrieve all elements within a specified element that have a specific tag name. This method returns an HTMLCollection of elements in the order they appear in the document. This guide provides a comprehensive overview of the getElementsByTagName() method, including syntax, usage, practical examples, and important considerations.

What is the getElementsByTagName() Method?

The getElementsByTagName() method is used to select all descendant elements of a particular element that match a specified tag name. The method traverses the DOM from the specified element, collecting all elements with the given tag name into an HTMLCollection.

Purpose of the getElementsByTagName() Method

The primary purpose of the getElementsByTagName() method is to provide a way to:

  • Select all child elements of a specific tag name.
  • Traverse and manipulate specific types of elements within a document.
  • Implement dynamic content manipulation based on tag names.
  • Create more targeted and efficient DOM interactions.

Syntax

The syntax for using the getElementsByTagName() method is as follows:

const elements = element.getElementsByTagName(tagName);

Where:

  • element: The HTML element from which to search for child elements.
  • tagName: A string representing the tag name to search for (e.g., “div”, “p”, “span”).
  • elements: An HTMLCollection containing all elements with the specified tag name.

Parameters

Parameter Type Description
`tagName` String The tag name of the elements to retrieve. The special tag name “*” matches all elements.

Return Value

  • An HTMLCollection of elements with the specified tag name, in the order they appear in the document. If no elements are found, an empty HTMLCollection is returned.

Examples

Let’s explore some examples to illustrate how to use the getElementsByTagName() method effectively.

Basic Usage

The following example demonstrates how to select all <p> elements within a <div> element.

<div id="myDiv1">
  <p>This is the first paragraph.</p>
  <p>This is the second paragraph.</p>
  <span>This is a span.</span>
</div>

<script>
  const myDiv1 = document.getElementById("myDiv1");
  const paragraphs1 = myDiv1.getElementsByTagName("p");

  for (let i = 0; i < paragraphs1.length; i++) {
    paragraphs1[i].style.color = "blue";
  }
</script>

In this example, all <p> elements within the <div> with the ID “myDiv1” are selected and their text color is changed to blue.

Selecting All Elements

To select all elements within an element, use the "*" tag name.

<div id="myDiv2">
  <p>This is the first paragraph.</p>
  <span>This is a span.</span>
</div>

<script>
  const myDiv2 = document.getElementById("myDiv2");
  const allElements2 = myDiv2.getElementsByTagName("*");

  for (let i = 0; i < allElements2.length; i++) {
    allElements2[i].style.fontWeight = "bold";
  }
</script>

Here, all elements within the <div> with the ID “myDiv2” are selected and their font weight is set to bold.

Nesting getElementsByTagName()

You can nest getElementsByTagName() calls to select elements within elements.

<div id="outerDiv3">
  <div id="innerDiv3">
    <p>This is a paragraph in the inner div.</p>
  </div>
</div>

<script>
  const outerDiv3 = document.getElementById("outerDiv3");
  const innerDiv3 = outerDiv3.getElementsByTagName("div")[0];
  const paragraphs3 = innerDiv3.getElementsByTagName("p");

  for (let i = 0; i < paragraphs3.length; i++) {
    paragraphs3[i].style.fontSize = "20px";
  }
</script>

In this case, the first getElementsByTagName("div") selects the inner <div>, and the second getElementsByTagName("p") selects all <p> elements within the inner <div>. The font size of the paragraphs is then set to 20px.

Using getElementsByTagName() with document

You can also use getElementsByTagName() directly on the document object to select all elements of a specific tag name in the entire document.

<p>This is the first paragraph in the document.</p>
<p>This is the second paragraph in the document.</p>

<script>
  const allParagraphs4 = document.getElementsByTagName("p");

  for (let i = 0; i < allParagraphs4.length; i++) {
    allParagraphs4[i].style.fontStyle = "italic";
  }
</script>

This example selects all <p> elements in the entire document and sets their font style to italic.

Example with Canvas

Here’s an example using getElementsByTagName() to manipulate canvas elements:

<canvas id="myCanvas5" width="200" height="100" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML canvas tag.</canvas>
<script>
var c5 = document.getElementsByTagName("canvas")[0];
var ctx5 = c5.getContext("2d");
ctx5.fillStyle = "#FF0000";
ctx5.fillRect(0,0,150,75);
</script>

In this example, the first canvas element on the page is retrieved, and a red rectangle is drawn on it.

Important Considerations

  • HTMLCollection is live: The HTMLCollection returned by getElementsByTagName() is a live collection. This means that if the DOM is modified, the HTMLCollection is automatically updated.
  • Performance: While getElementsByTagName() is generally efficient, using it excessively in performance-critical code can impact performance, especially in large documents. Consider caching the results or using more targeted selectors if performance is a concern.
  • Case-Insensitivity: The tagName parameter is case-insensitive in HTML documents. However, it’s case-sensitive in XML documents.
  • Specificity: getElementsByTagName() returns all elements with the specified tag name, regardless of their position in the DOM. To select elements with more specific criteria, consider using querySelector() or querySelectorAll().
  • Alternatives: If you need to select elements based on CSS selectors or more complex criteria, consider using querySelector() or querySelectorAll() for more flexibility. 💡

Real-World Applications of the getElementsByTagName() Method

The getElementsByTagName() method can be used in a variety of real-world applications, including:

  • Dynamic Content Filtering: Filtering and displaying content based on tag names.
  • Form Validation: Selecting specific form elements for validation.
  • Content Highlighting: Highlighting specific types of content within a document.
  • Accessibility Enhancements: Manipulating elements for accessibility purposes, such as adding ARIA attributes.

Browser Support

The getElementsByTagName() method is supported by all major web browsers, ensuring broad compatibility.

Conclusion

The getElementsByTagName() method is a valuable tool for selecting elements by their tag name within the DOM. By understanding its syntax, usage, and important considerations, you can effectively use this method to manipulate and interact with HTML elements in your web applications. Whether you’re selecting paragraphs, divs, or any other HTML element, getElementsByTagName() provides a straightforward way to access and manipulate elements based on their tag name.