Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

JavaScript Dictionary

  1. Home
  2. JavaScript Dictionary
  3. document.getElementById()

document.getElementById() Since: DOM Level 1(1998)

Retrieves the HTML element with the specified ID from the document. Because IDs must be unique within a page, this method always returns exactly one element.

Syntax

var element = document.getElementById("id");

Arguments

ArgumentDescription
idThe ID of the HTML element you want to retrieve, specified as a string. The # prefix is not needed.

Return Value

Returns the HTML element (an Element object) with the specified ID. If no matching element is found, returns null.

Sample Code

<h1 id="title">Main Title</h1>
<p id="description">This is a description.</p>
var title = document.getElementById("title");
console.log(title.textContent); // Outputs "Main Title"

var desc = document.getElementById("description");
desc.textContent = "The description has been updated.";

When an Element Is Not Found

Specifying an ID that does not exist returns null. Attempting to manipulate a null value will throw an error. Just like with document.querySelector(), always perform a null check before operating on the result.

// Specifying an ID that does not exist.
var el = document.getElementById("nothing");
el.innerHTML = "<p>test</p>"; // TypeError: Cannot set properties of null

// Correct approach
var el = document.getElementById("title");
if (el) {
	el.innerHTML = "<p>New Title</p>";
}

Overview

document.getElementById() is the simplest method for retrieving an HTML element by its ID. Because an ID must be unique within a page, it always returns exactly one element.

You can also retrieve an element by ID using document.querySelector("#id"), but document.getElementById() is faster internally, so it is recommended when selecting by ID.

Pass only the ID string as the argument. Unlike CSS selectors, you do not include the # prefix. Including # will cause the lookup to fail.

document.getElementById() is covered in more detail in the tutorial Targeting elements by ID and manipulating their attributes.

Browser Compatibility

Chrome Chrome
49+
Supported in all versions
Firefox Firefox
57+
Supported in all versions
Safari Safari
18+
Supported in all versions
Edge Edge
80+
11 or earlier ×
IE IE
11+
4.5 or earlier ×
Opera Opera
48+
6 or earlier ×
iOS Safari iOS Safari
18+
Supported in all versions
Android Browser Android Browser
37+
4 or earlier ×
Chrome Android Chrome Android
36+
17 or earlier ×
Firefox Android Firefox Android
79+
3 or earlier ×

If you find any errors or copyright issues, please .