1
What does document.getElementById() return?
1 Answer
1
The document.getElementById() method returns the
DOM element whose id attribute matches the specified value.
- If an element with the specified ID exists, it returns that Element object.
- If no matching element is found, it returns
null.
Syntax
document.getElementById(id);
id: A string representing the id attribute of the element to retrieve.
Example 1: Element Found
HTML
<h1 id="title">Welcome</h1>
JavaScript
// Get the element with id="title"
const heading = document.getElementById("title");
// Display the element
console.log(heading);
// Access its text content
console.log(heading.textContent);
Output
<h1 id="title">Welcome</h1>
Welcome
Example 2: Element Not Found
// Try to get an element that doesn't exist
const element = document.getElementById("unknown");
// Display the result
console.log(element);
Output
null
Important Notes
- IDs should be unique within an HTML document.
- The method returns only the first matching element (though duplicate IDs are invalid HTML).
- Since it may return
null, it's good practice to check the result before using it.
const button = document.getElementById("submitBtn");
if (button !== null) {
console.log("Button found!");
} else {
console.log("Button not found.");
}
Summary
| Situation | Return Value |
|---|---|
| Matching element exists | The corresponding DOM Element |
| No matching element exists | null |
document.getElementById() is one of the most commonly used DOM methods for selecting a specific element by its unique
id.