Edit Template
  • Home
  • /
  • JS getElementsByTagName
Edit Template
  • Home
  • /
  • JS getElementsByTagName

JavaScript getElementsByTagName()

The getElementsByTagName() method allows you to select all elements on a web page that match a specific HTML tag (like p, div, li, etc.). It returns a live HTMLCollection, which updates if the DOM changes.

Syntax

				
					document.getElementsByTagName("tagName");

				
			
  • "tagName" is the name of the HTML tag you want to target (like "p", "h1", "img", etc.).

  • The method returns a live collection, meaning changes in the DOM are automatically reflected.

Example HTML

				
					<p>This is a paragraph</p>
<p>This is another paragraph</p>
<p>Third paragraph here</p>

				
			

Example JavaScript

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

for (let i = 0; i < paragraphs.length; i++) {
  paragraphs[i].innerHTML = `Paragraph ${i + 1} modified by Learn With Arshyan`;
}

				
			

This code changes the text of all <p> tags dynamically.

Key Features

FeatureDescription
Live CollectionAutomatically reflects added/removed elements in real time
Tag-Based SelectionSelects all elements by tag name (p, ul, table, etc.)
 Case Sensitive"div""DIV" – always use lowercase to match HTML properly

When to Use getElementsByTagName()

  • When applying the same style or content to all elements of the same tag (e.g., all paragraphs or headings).

  • Useful in dynamic websites where content structure follows consistent tags.

  • Great for mass manipulation of lists, tables, or forms.

Summary

  • When applying the same style or content to all elements of the same tag (e.g., all paragraphs or headings).

  • Useful in dynamic websites where content structure follows consistent tags.

  • Great for mass manipulation of lists, tables, or forms.

Using getElementsByTagName() is an efficient way to manage multiple elements of the same type and build dynamic behaviors into your web pages.

Scroll to Top