Document

document.getElementsByTagName

Returns a live HTMLCollection of elements with the given tag name

Syntax

JavaScript
document.getElementsByTagName(tagName)

Parameters

ParameterTypeDescription
tagNamestringThe tag name to search for, or '*' for all elements

Return Value

A live HTMLCollection of found elements

Examples

Basic Usage
const paragraphs = document.getElementsByTagName('p')
console.log('Found', paragraphs.length, 'paragraphs')
Practical Example
const images = document.getElementsByTagName('img')
Array.from(images).forEach(img => {
  (img as HTMLImageElement).loading = 'lazy'
})
Advanced Usage
const allElements = document.getElementsByTagName('*')
console.log('Total elements:', allElements.length)

Understanding document.getElementsByTagName

The document.getElementsByTagName method in JavaScript returns a live HTMLCollection of elements with the given tag name. It belongs to the Document object and is one of the most widely used methods for working with document values in modern JavaScript and TypeScript applications.

The method signature is document.getElementsByTagName(tagName). It accepts 1 parameter: tagName. When called, it returns a live htmlcollection of found elements. Understanding when and how to use getElementsByTagName() helps you write more expressive, readable code.

Common use cases for document.getElementsByTagName include data transformation, input validation, API response processing, and building reusable utility functions. It works well alongside related methods like dom-queryselectorall, dom-getelementsbyclassname, dom-getelementbyid, enabling you to chain operations together for complex data manipulation pipelines.

Browser support for document.getElementsByTagName is excellent across all modern browsers including Chrome, Firefox, Safari, and Edge. It is also fully supported in Node.js and Deno. For older environments, transpilation with Babel or a polyfill may be needed.

Browser Compatibility

Supported in all modern browsers (Chrome, Firefox, Safari, Edge) and Node.js. Part of the ECMAScript standard.

Related Methods

More Document Methods

Other methods in the Document object

Related Tools

More Document Methods

Explore JavaScript Methods

Browse our complete reference of 410 JavaScript methods with syntax, examples, and explanations.