JavaScript getElementsByTagName

The getElementsByTagName() method is one of the most fundamental tools in a web developer's arsenal for DOM manipulation. It allows you to search the entire document (or a specific parent element) and gather every instance of a specific HTML tag into a single, manageable list.

Usage:

  • The getElementsByTagName() method is called on the document object (or any specific element) to select all child elements that match a specific HTML tag name.
  • It is particularly useful when you need to apply bulk changes, such as styling every link on a page or gathering all input values from a form.
Developer Tip: You can call this method on specific elements, not just document. For example, myDiv.getElementsByTagName('p') will only find paragraphs inside that specific div, which is great for performance and scoping.

Syntax:

var elements = document.getElementsByTagName(tagName);
  • tagName: A string representing the HTML tag you want to find. For example, 'div', 'p', 'span', or 'button'.
  • Pass the special string '*' as the tag name to select every single element within the document or the parent container.

Return Value:

  • The method returns a live HTMLCollection. This is an array-like object containing all the elements found, in the order they appear in the source code.
  • If no matching elements are found, it doesn't return null; instead, it returns an empty HTMLCollection with a length of 0.
Common Mistake: Beginners often forget that getElementsByTagName returns a collection, not a single element. Even if there is only one <h1> on your page, you still have to access it via index: document.getElementsByTagName('h1')[0].

Example:

In this example, we will select all <div> elements and see how they are stored.

<div>Div Element 1</div>
<div>Div Element 2</div>
<p>A paragraph element</p>
var divElements = document.getElementsByTagName('div');

console.log(divElements.length); // Output: 2
console.log(divElements[0].innerText); // Output: "Div Element 1"

Accessing Elements:

  • Since an HTMLCollection is array-like, you can access individual elements using index notation (starting at 0).
  • You can find out how many elements were gathered by checking the .length property.
  • To perform an action on every element (like changing the color of all paragraphs), you can use a standard for loop.
Best Practice: While HTMLCollection is array-like, it doesn't support modern array methods like .forEach(), .map(), or .filter(). Use Array.from(collection) or the spread operator [...collection] to convert it into a true array if you need these helper functions.

Live Collection:

  • A unique feature of getElementsByTagName is that the returned collection is live.
  • If you select all <li> elements and then later add another <li> to the DOM via JavaScript, the collection will automatically update to include the new element without you needing to call the method again.
Watch Out: Because the collection is "live," be careful when looping through it and adding new elements of the same tag name. You could accidentally create an infinite loop where the collection keeps growing as you iterate.

Null Handling:

  • One of the safest aspects of this method is that it is very robust. If you search for a tag that doesn't exist (like 'marquee' in a modern app), it simply returns an object with a length of 0.
  • Always check the length property before trying to access specific indices to avoid "undefined" errors.

Use Cases:

  • Global Formatting: Finding all <a> tags to ensure they all have a specific target="_blank" attribute.
  • Form Processing: Selecting all <input> tags within a specific form to validate their data.
  • Web Scraping: Extracting data from tables by selecting all <tr> or <td> tags.

 

Key Points

  • getElementsByTagName() is a legacy method supported by every browser in existence, making it extremely reliable.
  • It returns a live HTMLCollection, meaning the list stays in sync with changes to the DOM.
  • It is case-insensitive in HTML ('DIV' is the same as 'div'), but case-sensitive in XML/XHTML.
  • It is an excellent choice for broad, tag-based selections where you don't need the specific complexity of CSS selectors (which querySelectorAll provides).