H.dev

getElementsByTagName()

Selecting by HTML Tags

Sometimes you don't care about IDs or Classes. Sometimes you just want to grab every single <p> tag on the page, or every single <img> tag to apply a bulk change.

For this, we use document.getElementsByTagName().

How it Works

You pass the string name of the HTML tag you want to find (e.g., "p", "div", "h1"). It will search the entire document and return an HTMLCollection of all matching elements.

HTML:

<p>First paragraph.</p>
<div>A random div.</div>
<p>Second paragraph.</p>

JavaScript:

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

console.log(allParagraphs.length); // 2

Practical Example

Imagine you are building a "Dark Mode" toggle button using Vanilla JavaScript, and you need to change the text color of every single link (<a> tag) on the page to white.

let allLinks = document.getElementsByTagName("a");

for (let i = 0; i < allLinks.length; i++) {
    allLinks[i].style.color = "white";
}

💡 Himanshu's Tip:

If you want to grab EVERY single element on the webpage (literally everything inside the body), you can pass a wildcard asterisk into the method: document.getElementsByTagName("*"). Be careful though, this will return a massive collection!

Interview Questions

  1. Does getElementsByTagName require the angle brackets in the string argument (e.g., "<p>" vs "p")?
  2. What does this method return if there are absolutely no matching tags on the page?
  3. If you want to change the style of all returned tags, why do you have to use a for loop?

Design & Developed by Himanshu Dubey © 2026