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
sample_getElementById.html
<h1 id="fighter-name">Yagami Iori</h1> <p id="fighter-style">Yagami-ryu Old Fighting Style</p> <p id="fighter-age">20</p> <button id="btn-update">Update Info</button>
sample_getElementById.js
// Pattern 1: Get text content
var nameEl = document.getElementById("fighter-name");
console.log(nameEl.textContent); // Outputs "Yagami Iori"
var styleEl = document.getElementById("fighter-style");
console.log(styleEl.textContent); // Outputs "Yagami-ryu Old Fighting Style"
// Pattern 2: Update text content
var ageEl = document.getElementById("fighter-age");
ageEl.textContent = "Age: 20";
// Pattern 3: Modify an attribute
var btn = document.getElementById("btn-update");
btn.setAttribute("disabled", "true");
btn.textContent = "Updated";
// Pattern 4: Check for null before operating
var el = document.getElementById("nonexistent");
if (el) {
el.textContent = "Element found.";
} else {
console.log("Element not found."); // Outputs when the element does not exist.
}
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.getElementById("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.