H.dev

getElementById()

The Sharpshooter Selector

Before you can change an HTML element using JavaScript, you first have to "select" or "find" it in the DOM.

The easiest and most common way to grab a single, specific element is by using the document.getElementById() method.

How it Works

In HTML, the id attribute is meant to be completely unique. No two elements on the same page should ever share the same ID. Because of this, getElementById() is the most efficient and exact way to find an element.

HTML:

<h1 id="main-title">Welcome to my Portfolio</h1>

JavaScript:

let headingElement = document.getElementById("main-title");
console.log(headingElement); // Returns the actual HTML h1 node

Storing in Variables

Notice how we stored the result in a variable called headingElement? Once an element is selected and stored in a variable, you have total control over it. You can change its text, change its color, or hide it completely!

// Changing the text color to red!
let headingElement = document.getElementById("main-title");
headingElement.style.color = "red";

💡 Himanshu's Tip:

When passing the ID string into the method, do NOT include a hashtag (#). While CSS uses #main-title, this JavaScript method specifically asks for just the name, so you write "main-title".

Interview Questions

  1. Why does getElementById() only return a single element instead of a list?
  2. What does document.getElementById() return if the ID you provided does not exist in the HTML?
  3. Should you use getElementById to select multiple elements that share the same class?

Design & Developed by Himanshu Dubey © 2026