Back to course

Selecting Elements: getElementById()

JavaScript: The Complete '0 to Hero' Beginner Course

79. Selecting Elements: getElementById()

To manipulate an element, we first have to select (find) it in the DOM tree. The simplest way is using an ID.

IDs Must Be Unique

In HTML, the id attribute is designed to be unique across the entire document. This makes getElementById() very fast and reliable.

Syntax

javascript const element = document.getElementById('element-id');

Example

Given the HTML:

html

Welcome

javascript const heading = document.getElementById('main-heading');

console.log(heading); // Outputs the HTML element node

// Check if the element was found if (heading) { heading.textContent = 'Welcome, User!'; }

Note: If the ID is not found, getElementById() returns null.