JavaScript getElementById() Method

Summary: in this tutorial, you will learn how to use the JavaScript getElementById() to select an element by an id.

Introduction to JavaScript getElementById() method #

The getElementById() method of the document object returns an HTML element with the specified id.

Here’s the syntax of the getElementById() method:

const element = document.getElementById(id);

In this syntax:

  • id is a string that represents the id of the element to select.

Note that the method matches ID case-sensitively. For example, the 'root' and 'Root' are different.

If the document has no element with the specified id, the getElementById() method returns null.

Unlike the querySelector() method, the getElementById() is only available on the document object, not on other DOM elements.

Typically, the id is unique within an HTML document. However, HTML is forgiving, and a non-well-formed HTML may have multiple elements with the same id. In this case, the getElementById() method returns the first element it encounters.

JavaScript getElementById() method example #

Suppose you have a document with two p elements:

<p id="first">Hi, There!</p>
<p>JavaScript is fun.</p>

The following code shows how to get the element with the id first:

const elem = document.getElementById("first");

See the following demo:

Note that after selecting the element, you can apply styles, manipulate its attributes, and traverse to parent and child elements.

Summary #

  • The document.getElementById() returns a DOM element specified by an id or null if no matching element is found.
  • If multiple elements have the same id, even though it is invalid, the getElementById() returns the first element it encounters.

Quiz #

Quiz

getElementById() Method

10 questions

To help you understand and use the getElementById() effectively.

Was this helpful?