document.getElementsByTagName
Returns a live HTMLCollection of elements with the given tag name
Syntax
document.getElementsByTagName(tagName)Parameters
| Parameter | Type | Description |
|---|---|---|
| tagName | string | The tag name to search for, or '*' for all elements |
Return Value
A live HTMLCollection of found elements
Examples
const paragraphs = document.getElementsByTagName('p')
console.log('Found', paragraphs.length, 'paragraphs')const images = document.getElementsByTagName('img')
Array.from(images).forEach(img => {
(img as HTMLImageElement).loading = 'lazy'
})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
document.querySelectorAllReturns a static NodeList representing a list of the document's elements that match the specified group of CSS selectors
document.getElementsByClassNameReturns a live HTMLCollection of all child elements which have all of the given class names
document.getElementByIdReturns an Element object representing the element whose id property matches the specified string
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.