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
| Argument | Description |
|---|---|
| id | The 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
4.5 or earlier ×
6 or earlier ×
Android Browser
37+ ○
4 or earlier ×
Chrome Android
36+ ○
17 or earlier ×
Firefox Android
79+ ○
3 or earlier ×If you find any errors or copyright issues, please contact us.