JavaScriptDOM and events

document.getElementById()

Returns the element with the given identifier (the id attribute), or null when there isn’t one.

Returns
The element with the given id, or null.
On this page

Example

#
JavaScript
const title = document.getElementById('title')

console.log(title)
console.log(title.textContent)
console.log(document.getElementById('#title'))
console.log(document.getElementById('Title'))
Console
<h1 id="title">
World 1: Ancient Egypt
null
null

Definition and usage

#

The getElementById() method returns the element whose id attribute equals the given string. You pass just the name, without the # character, since this isn’t a CSS selector. Case matters.

An id should be unique across the whole document. If several elements end up sharing the same id by mistake, the method returns the first one. When there’s no such element, the result is null.

This is the oldest and simplest way to get an element. It only works on the document object, not on individual elements. In newer code you’ll just as often see document.querySelector("#id"), which gives the same result but accepts any selector.

Syntax

#
Syntax
document.getElementById(id)

Parameters

#
  • id

    string

    The value of the id attribute of the element you’re looking for, without the # character.

More examples

#
Updating a counter
JavaScript
const points = document.getElementById('points')

points.textContent = Number(points.textContent) + 30
console.log(points.textContent)
Console
150
The same element as with querySelector()
JavaScript
const byId = document.getElementById('start-btn')
const bySelector = document.querySelector('#start-btn')

console.log(byId === bySelector)
Console
true

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • Don’t add a # before the name. getElementById("#menu") looks for an element with id="#menu" and returns null.
  • Keep every id unique. Duplicate identifiers also break form labels and links to page sections.
  • Don’t rely on the browser creating global variables named after your ids. Always get elements explicitly.

Related entries

#

Spotted a mistake or missing an example? Write to us.