0
0
JavascriptHow-ToBeginner · 3 min read

How to Select Element by Tag in JavaScript: Simple Guide

To select elements by tag in JavaScript, use document.getElementsByTagName('tagName') which returns a live HTMLCollection of all elements with that tag. For a single element, you can access it by index or use document.querySelector('tagName') to get the first matching element.
📐

Syntax

The main method to select elements by tag name is document.getElementsByTagName('tagName'). It returns a live collection of all elements with the specified tag. You can also use document.querySelector('tagName') to get the first element matching the tag.

  • document.getElementsByTagName('tagName'): Returns all elements with the tag.
  • document.querySelector('tagName'): Returns the first element with the tag.
javascript
const elements = document.getElementsByTagName('p');
const firstElement = document.querySelector('p');
💻

Example

This example selects all <p> tags on the page and logs their text content. It also shows how to get the first <p> element.

javascript
const paragraphs = document.getElementsByTagName('p');
console.log('All paragraphs:');
for (let i = 0; i < paragraphs.length; i++) {
  console.log(paragraphs[i].textContent);
}

const firstParagraph = document.querySelector('p');
console.log('First paragraph:', firstParagraph.textContent);
Output
All paragraphs: This is paragraph one. This is paragraph two. First paragraph: This is paragraph one.
⚠️

Common Pitfalls

One common mistake is treating the result of getElementsByTagName like an array. It returns an HTMLCollection, which is similar but not exactly an array, so array methods like forEach won't work directly.

Also, getElementsByTagName returns a live collection, meaning it updates automatically if the DOM changes, which can cause unexpected behavior.

javascript
/* Wrong: Using forEach directly on HTMLCollection */
const divs = document.getElementsByTagName('div');
// divs.forEach(div => console.log(div)); // Error: forEach is not a function

/* Right: Use a for loop or convert to array */
for (let i = 0; i < divs.length; i++) {
  console.log(divs[i]);
}

// Or convert to array
Array.from(divs).forEach(div => console.log(div));
📊

Quick Reference

MethodDescriptionReturns
document.getElementsByTagName('tagName')Selects all elements with the given tagLive HTMLCollection
document.querySelector('tagName')Selects the first element with the given tagSingle Element or null
document.querySelectorAll('tagName')Selects all elements with the given tagStatic NodeList

Key Takeaways

Use document.getElementsByTagName('tagName') to get all elements by tag as a live collection.
Use document.querySelector('tagName') to get the first element with that tag.
HTMLCollection is not a true array; use loops or Array.from() to iterate.
getElementsByTagName returns a live collection that updates with DOM changes.
For static lists, consider document.querySelectorAll('tagName') which returns a static NodeList.