Get Element By ID
Select a single element by its ID using getElementById — the fastest and most direct way to grab an element from the DOM.
Get Element By ID
The simplest way to select an element is by its ID. Since IDs must be unique on a page, getElementById always returns a single element (or null if not found).
Using getElementById
<h1 id="page-title">Hello World</h1>
<p id="description">This is a paragraph.</p>
<script>
var title = document.getElementById('page-title');
console.log(title); // The <h1> element
console.log(title.textContent); // "Hello World"
var desc = document.getElementById('description');
console.log(desc.textContent); // "This is a paragraph."
</script>
What It Returns
| Scenario | Return Value |
|---|---|
| Element with matching ID exists | The HTML element object |
| No element with that ID | null |
| Multiple elements with same ID (invalid HTML) | The first match |
Working with the Element
var title = document.getElementById('page-title');
// Read properties
console.log(title.id); // "page-title"
console.log(title.className); // CSS classes as a string
console.log(title.tagName); // "H1"
console.log(title.innerHTML); // Inner HTML content
console.log(title.textContent); // Text without HTML tags
// Modify the element
title.textContent = 'New Title';
title.style.color = 'crimson';
Key Takeaways
document.getElementById('id')returns a single element by its ID- Returns
nullif no element with that ID exists - IDs must be unique per page — this method always returns one element
- You can read and modify properties like
textContent,innerHTML,style, andclassName