← Back to all tutorials

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

ScenarioReturn Value
Element with matching ID existsThe HTML element object
No element with that IDnull
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 null if 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, and className