Table of Contents

The JavaScript getElementsByTagName() method allows you to select HTML elements by their tag name, such as p, div, h1, or input. It returns a live collection of matching elements, making it useful when you need to access or update multiple elements of the same type in the Document Object Model (DOM).

What Is getElementsByTagName() in JavaScript?

getElementsByTagName() is a DOM method available on the Document and Element interfaces. It searches the relevant document or element subtree for elements with the specified tag name and returns an HTMLCollection containing the matches.

For example, document.getElementsByTagName("p") selects all paragraph elements in the document. You can then read their content, change their styles, or perform other DOM operations.

Syntax of getElementsByTagName()

document.getElementsByTagName(tagName);

Parameter: tagName is a string containing the tag name of the elements to find, such as "p", "div", or "h2".

Return value: A live HTMLCollection containing the matching elements in document order. If there are no matches, the collection is empty and its length is zero.

1. Select All Elements by Tag Name

In this example, getElementsByTagName("p") selects every paragraph element in the document. The length property tells you how many paragraphs were found.

<p>First paragraph</p>
<p>Second paragraph</p>
<p>Third paragraph</p>

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

  console.log(paragraphs.length); // 3
  console.log(paragraphs[0].textContent); // First paragraph
</script>

The collection uses zero-based indexing, so the first matching element is at index 0, the second at index 1, and so on.

2. Change the Content of Multiple Elements

You can loop through the returned HTMLCollection to update every matching element. The following example changes the text of all paragraph elements.

<p>Welcome to JavaScript</p>
<p>Learn DOM methods</p>
<p>Practice with examples</p>

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

  for (let i = 0; i < paragraphs.length; i++) {
    paragraphs[i].textContent = "Paragraph updated!";
  }
</script>

After the script runs, each paragraph displays the updated text. The textContent property is a good choice for inserting plain text because it does not parse the value as HTML.

3. Change the CSS Style of Elements

The method can also help you apply the same style to several elements. This example changes the text color and font size of every heading level two element.

<h2>JavaScript Basics</h2>
<h2>JavaScript DOM</h2>
<h2>JavaScript Events</h2>

<script>
  const headings = document.getElementsByTagName("h2");

  for (const heading of headings) {
    heading.style.color = "blue";
    heading.style.fontSize = "28px";
  }
</script>

All matching h2 elements receive the same inline styles. For larger applications, CSS classes are often easier to maintain than setting many individual style properties with JavaScript.

4. Select Elements Inside a Specific Parent

You do not have to search the entire document. Because getElementsByTagName() is also available on elements, you can call it on a parent element to search only within that element’s descendants.

<div id="content">
  <p>First paragraph inside the div</p>
  <p>Second paragraph inside the div</p>
</div>

<p>Paragraph outside the div</p>

<script>
  const container = document.getElementById("content");
  const paragraphs = container.getElementsByTagName("p");

  console.log(paragraphs.length); // 2
</script>

Only paragraph elements inside the element with the ID content are included. The paragraph outside the container is not part of this collection.

5. Select Every Element in the Document

You can pass an asterisk ("*") to select all elements in the document. This can be useful for inspecting the page or applying a temporary operation to every element.

const allElements = document.getElementsByTagName("*");

console.log("Total elements:", allElements.length);

for (const element of allElements) {
  console.log(element.tagName);
}

The returned collection contains element nodes, not text nodes or comment nodes. Use this broad selection carefully because a page can contain a large number of elements.

6. Access HTMLCollection Items

The result is an HTMLCollection, which supports indexed access and properties such as length. You can use a standard for loop or a for...of loop to process its elements.

const listItems = document.getElementsByTagName("li");

// Access an item by index
console.log(listItems[0]);

// Read the number of matching elements
console.log(listItems.length);

// Loop through the collection
for (const item of listItems) {
  console.log(item.textContent);
}

An HTMLCollection is not an Array, so Array methods such as map() and filter() are not directly available on it. Convert it to an Array when you need those methods.

7. Convert HTMLCollection to an Array

Use Array.from() or the spread syntax to create an Array from the collection. The resulting Array is a snapshot of the elements at the time of conversion.

const paragraphs = document.getElementsByTagName("p");

// Convert HTMLCollection to an Array
const paragraphArray = Array.from(paragraphs);

// Use an Array method
const paragraphTexts = paragraphArray.map((paragraph) => {
  return paragraph.textContent;
});

console.log(paragraphTexts);

The spread syntax provides another option:

const paragraphArray = [...document.getElementsByTagName("p")];

8. Understand the Live HTMLCollection

The HTMLCollection returned by getElementsByTagName() is live. It automatically reflects matching elements added to or removed from the relevant part of the document.

<p>First paragraph</p>

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

  console.log(paragraphs.length); // 1

  const newParagraph = document.createElement("p");
  newParagraph.textContent = "Second paragraph";
  document.body.appendChild(newParagraph);

  console.log(paragraphs.length); // 2
</script>

Notice that the original paragraphs collection now contains two elements, even though you did not call the method again. This is the behavior of a live collection.

Important: Be careful when removing elements while looping forward through a live HTMLCollection. Removing an item changes the collection and shifts later indexes. One safe approach is to work on a static Array copy:

const paragraphs = Array.from(
  document.getElementsByTagName("p")
);

for (const paragraph of paragraphs) {
  paragraph.remove();
}

9. getElementsByTagName() vs. querySelectorAll()

Both methods can select elements by tag name, but their return values and selection syntax are different.

// Returns a live HTMLCollection
const liveParagraphs = document.getElementsByTagName("p");

// Returns a static NodeList
const staticParagraphs = document.querySelectorAll("p");

getElementsByTagName() accepts a tag name and returns a live HTMLCollection. querySelectorAll() accepts a CSS selector and returns a static NodeList. Use querySelectorAll() when you need more flexible selectors, such as "section p" or "input[type='text']".

10. Common Mistakes and Best Practices

  • Forgetting the tag name: Pass a tag name such as "p" or "div", not an ID selector such as "#content".
  • Expecting one element: The method returns an HTMLCollection. Use an index such as elements[0] if you need the first match, and check the collection length first.
  • Assuming the result is an Array: Convert it with Array.from() before using Array-only methods such as map() or filter().
  • Ignoring live collection behavior: The collection updates as matching elements are added or removed. Use an Array copy when you need a stable list.
  • Searching the wrong scope: Calling the method on document searches the document. Calling it on an element searches that element’s descendants.
  • Running the script before the markup exists: Place the script after the relevant HTML or wait for DOMContentLoaded.

Categorized in:

Javascript, Js DOM,