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

 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");

output

<p id="first">Hi, There!</p>

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.

Categorized in:

Javascript, JS DOM,