The JavaScript getElementsByTagName() method is used to select HTML elements based on their tag names. It allows you to access multiple elements with the same HTML tag, such as <p>, <h1>, <div>, or <li>, and modify their content or styles using JavaScript.
For example, if a webpage contains several paragraph elements, you can use getElementsByTagName() to select all of them and change their text color.
In this tutorial, you will learn what getElementsByTagName() is, its syntax, how it works, practical examples, common mistakes, and best practices.
What Is getElementsByTagName() in JavaScript?
The getElementsByTagName() method is a DOM method that selects HTML elements based on their tag names and returns a live HTMLCollection containing the matching elements.
Unlike getElementById(), which selects an element by its ID, getElementsByTagName() can select multiple elements that use the same HTML tag.
Consider the following HTML example:<p>Learn HTML</p>
<p>Learn CSS</p>
<p>Learn JavaScript</p>
You can select all three paragraph elements using JavaScript:
const paragraphs = document.getElementsByTagName("p");
console.log(paragraphs);
The returned collection contains all three paragraph elements because they use the <p> tag.
This method is useful when you want to perform the same operation on multiple elements of a particular type.
Syntax of getElementsByTagName()
The syntax of the getElementsByTagName() method is:
document.getElementsByTagName("tagName");
Here is what each part means:
| Component | Description |
|---|---|
document | Represents the current HTML document. |
getElementsByTagName() | Selects elements by their tag names. |
"tagName" | The HTML tag name you want to select. |
For example:
document.getElementsByTagName("p");
This statement selects all paragraph elements in the document.
Similarly, you can select headings, divisions, images, links, lists, or other HTML elements.
document.getElementsByTagName("h1");
document.getElementsByTagName("div");
document.getElementsByTagName("img");
document.getElementsByTagName("a");
Important: Do not include angle brackets when specifying the tag name. Use "p" instead of "<p>".
How to Use getElementsByTagName() in JavaScript
Let’s create a simple HTML page containing multiple paragraph elements.
The console displays an HTMLCollection containing the three paragraph elements.
Let’s understand how this code works:
- The HTML document contains three
<p>elements. getElementsByTagName("p")selects all paragraph elements.- The selected elements are stored in the
paragraphsvariable. console.log(paragraphs)displays the collection in the browser console.
The method returns an HTMLCollection, not a regular array.
Change Text Color Using getElementsByTagName()
You can use getElementsByTagName() to select multiple elements and modify their CSS styles with a loop.
For example, the following code changes the text color of every paragraph to blue.
When you click the Change Color button, all three paragraphs turn blue.
The for loop iterates through the collection and accesses each paragraph using its index.
The statement paragraphs[i].style.color = "blue" changes the text color of the current paragraph.
This approach is useful for styling multiple elements, updating lists, and creating interactive webpages.
Access Individual Elements Using getElementsByTagName()
Although getElementsByTagName() selects multiple elements, you can access individual elements using their indexes.
Consider the following example:
<h2>HTML</h2>
<h2>CSS</h2>
<h2>JavaScript</h2>
<script>
const headings = document.getElementsByTagName("h2");
console.log(headings[0].textContent);
console.log(headings[1].textContent);
console.log(headings[2].textContent);
</script>
Output:
HTML CSS JavaScript
The first heading has index 0, the second has index 1, and the third has index 2.
You can also use the length property to count the matching elements.
const headings = document.getElementsByTagName("h2");
console.log(headings.length);
Output:
3
The length property returns the number of matching elements currently in the collection.
Remember that JavaScript indexes start at zero.
Select All HTML Elements Using getElementsByTagName()
You can use an asterisk (*) to select all elements within the specified document or element scope.
For example:
The asterisk selects all elements in the document, including the <html>, <head>, <body>, heading, paragraph, and button elements.
The exact count depends on the HTML structure.
This technique can be useful for inspecting document elements, although selecting every element is usually unnecessary for ordinary webpage interactions.
Select Elements Within Another Element
The getElementsByTagName() method can also be called on an individual HTML element rather than the entire document.
When you do this, it selects matching descendant elements within that element.
Consider this example:
<div id="container">
<p>First paragraph</p>
<p>Second paragraph</p>
</div>
<p>Outside paragraph</p>
<script>
const container = the document.getElementById("container");
const paragraphs = container.getElementsByTagName("p");
console.log(paragraphs.length);
</script>
Output:
2
The method selects only the two paragraph elements inside the container element.
The paragraph outside the container is not included.
This approach is useful when you need to work with elements inside a specific section of a webpage.
What Is a Live HTMLCollection?
One important feature of getElementsByTagName() is that it returns a live HTMLCollection.
A live collection automatically reflects changes to the document that affect which elements match the specified tag name.
Consider this example:
<p>First paragraph</p>
<p>Second paragraph</p>
<script>
const paragraphs = document.getElementsByTagName("p");
console.log(paragraphs.length);
const newParagraph = document.createElement("p");
newParagraph.textContent = "Third paragraph";
document.body.appendChild(newParagraph);
console.log(paragraphs.length);
</script>
Output:
2 3
Initially, the collection contains two paragraphs.
After JavaScript creates and appends a third paragraph, the collection automatically includes the new element.
You do not need to call getElementsByTagName() again to update the collection.
This behavior is useful to understand when dynamically adding or removing elements from a webpage.
getElementsByTagName() vs getElementsByClassName()
Both methods select multiple HTML elements, but they use different criteria.
| Feature | getElementsByTagName() | getElementsByClassName() |
|---|---|---|
| Selection method | HTML tag name | Class name |
| Example | getElementsByTagName("p") | getElementsByClassName("message") |
| Can select multiple elements | Yes | Yes |
| Return type | HTMLCollection | HTMLCollection |
| Live collection | Yes | Yes |
| Requires a CSS selector | No | No |
Use getElementsByTagName() when you want to select elements based on their HTML tag. Use getElementsByClassName() when you want to select elements based on their class names.
getElementsByTagName() vs querySelectorAll()
The querySelectorAll() method also allows you to select multiple elements, but it supports CSS selectors.
| Feature | getElementsByTagName() | querySelectorAll() |
|---|---|---|
| Selection | HTML tag names | CSS selectors |
| Return type | HTMLCollection | NodeList |
| Collection behavior | Live | Static |
| Select all paragraphs | getElementsByTagName("p") | querySelectorAll("p") |
| Select elements by class | Not directly | querySelectorAll(".message") |
| Supports complex selectors | No | Yes |
For example, both statements can select all paragraph elements:
const paragraphs1 = document.getElementsByTagName("p");
const paragraphs2 = document.querySelectorAll("p");
The main difference is that the first returns a live collection, while the second returns a static collection.
Use getElementsByTagName() for direct tag-based selection. Use querySelectorAll() when you need more flexible CSS selectors.
Common Mistakes When Using getElementsByTagName()
Including Angle Brackets in the Tag Name
The method accepts the tag name without HTML angle brackets.
Incorrect:
document.getElementsByTagName(“<p>”);
Correct:
document.getElementsByTagName(“p”);
Treating the Collection as a Single Element
The method returns an HTMLCollection, even if only one element matches.
Incorrect:
const paragraphs = document.getElementsByTagName("p");
paragraphs.style.color = "blue";
The collection itself does not have the individual element’s style property.
Correct:
const paragraphs = document.getElementsByTagName("p");
for (let i = 0; i < paragraphs.length; i++) {
paragraphs[i].style.color = "blue";
}
Forgetting That Indexes Start at Zero
Use paragraphs[0] to access the first paragraph, not paragraphs[1].
Running JavaScript Before Elements Exist
If your script runs before the relevant HTML elements have been parsed, the collection may initially be empty.
You can avoid this by placing your script after the relevant HTML elements or using an external script with the defer attribute.
Confusing Tag Names with Class Names
Use getElementsByTagName("p") to select paragraph elements.
Use getElementsByClassName("message") to select elements with the message class, regardless of their tag names.
Best Practices for Using getElementsByTagName()
Follow these practices when working with this method:
- Use the exact HTML tag name you want to select.
- Remember that the method returns an
HTMLCollection, not a regular array. - Use a loop when you need to modify every matching element.
- Call the method on a specific parent element when you only need its descendant elements.
- Remember that the collection is live and updates when matching elements change.
- Avoid selecting all elements with
"*"unless you have a specific reason. - Use
querySelectorAll()when your task requires more complex CSS selectors.
These practices help you write cleaner and more reliable JavaScript code.
Frequently Asked Questions
What does getElementsByTagName() do in JavaScript?
The getElementsByTagName() method selects elements based on their HTML tag names and returns them in a live HTMLCollection.
What is the syntax of getElementsByTagName()?
document.getElementsByTagName(“tagName”);
Replace tagName with the HTML tag you want to select, such as "p", "div", or "h1".
Can getElementsByTagName() select multiple elements?
Yes. It returns all matching elements within the specified document or element scope.
What does getElementsByTagName() return if no elements match?
It returns an empty HTMLCollection. Its length property is 0.
What does the asterisk mean in getElementsByTagName(“*”)?
The asterisk selects all descendant elements within the specified scope. When called on document, it selects all HTML elements in the document.
Is getElementsByTagName() case-sensitive?
For HTML documents, tag-name matching is generally case-insensitive. XML documents have different case-sensitivity rules.
What is the difference between getElementsByTagName() and getElementsByClassName()?
getElementsByTagName() selects elements based on their tag names, while getElementsByClassName() selects elements based on their class names.
Can I use forEach() directly on getElementsByTagName()?
No. HTMLCollection does not provide the standard array forEach() method. You can use a for loop or convert the collection into an array with Array.from().