document.getElementById() - JavaScript DOM Reference
Complete guide to getElementById() - syntax, return values, performance, common mistakes, and comparisons with querySelector and other DOM selection methods.
Syntax
const element = document.getElementById(id);
Returns the Element whose id attribute matches the given string, or null if no match is found. The search is case-sensitive and scoped to the entire document.
Parameters
| Parameter | Type | Description |
|---|---|---|
| id | String | The value of the id attribute to search for. Must be unique within the document. |
Basic Examples
// Get a single element by its ID
const header = document.getElementById('main-header');
// Read content
console.log(header.textContent);
// Modify content
header.textContent = 'Updated Title';
// Change styles
header.style.color = '#04122e';
header.style.fontSize = '2rem';
// Add a CSS class
header.classList.add('active');
// Set attributes
header.setAttribute('data-section', 'hero');
Return Value
getElementById() returns an Element object or null. Always check for null before accessing properties:
const el = document.getElementById('maybe-exists');
// Safe pattern - null check
if (el) {
el.textContent = 'Found it!';
}
// Optional chaining (modern browsers)
document.getElementById('maybe-exists')
?.classList.add('highlight');
Performance
getElementById() is the fastest DOM selection method because browsers maintain an internal hash map of element IDs. It runs in O(1) time regardless of document size.
| Method | Speed | Returns | Selector Type |
|---|---|---|---|
| getElementById() | Fastest (O(1)) | Element | null | ID only |
| querySelector() | Fast | Element | null | Any CSS selector |
| getElementsByClassName() | Fast | Live HTMLCollection | Class name |
| getElementsByTagName() | Fast | Live HTMLCollection | Tag name |
| querySelectorAll() | Slower | Static NodeList | Any CSS selector |
Common Mistakes
1. Including the # symbol
// WRONG - don't include #
document.getElementById('#header'); // returns null
// CORRECT
document.getElementById('header'); // returns element
2. Running before DOM is ready
// WRONG - script in <head> runs before body is parsed
const el = document.getElementById('app'); // null!
// CORRECT - wait for DOMContentLoaded
document.addEventListener('DOMContentLoaded', () => {
const el = document.getElementById('app'); // works
});
// ALSO CORRECT - place script at end of <body>
3. Duplicate IDs
If multiple elements share the same ID (invalid HTML), getElementById() returns only the first match. Always ensure IDs are unique.
getElementById vs querySelector
// These are equivalent
document.getElementById('nav');
document.querySelector('#nav');
// But getElementById is:
// ✓ Slightly faster (direct hash lookup)
// ✓ More explicit about intent
// ✗ Limited to IDs only
// querySelector can do more:
document.querySelector('.card:first-child');
document.querySelector('[data-role="admin"]');
document.querySelector('form input[required]');
Practical Patterns
// Form handling
const form = document.getElementById('signup');
form.addEventListener('submit', (e) => {
e.preventDefault();
const name = document.getElementById('name').value;
const email = document.getElementById('email').value;
console.log({ name, email });
});
// Toggle visibility
function togglePanel(id) {
const panel = document.getElementById(id);
panel.hidden = !panel.hidden;
}
// Dynamic content
function updateCounter(id, value) {
document.getElementById(id).textContent = value;
}
Last updated: 2026 • Browse all courses