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, ornull.
Example
#const title = document.getElementById('title')
console.log(title)
console.log(title.textContent)
console.log(document.getElementById('#title'))
console.log(document.getElementById('Title'))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
#document.getElementById(id)Parameters
#id
string
The value of theidattribute of the element you’re looking for, without the#character.
More examples
#const points = document.getElementById('points')
points.textContent = Number(points.textContent) + 30
console.log(points.textContent)const byId = document.getElementById('start-btn')
const bySelector = document.querySelector('#start-btn')
console.log(byId === bySelector)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 withid="#menu"and returnsnull. - Keep every
idunique. 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
#- querySelector() vs getElementById()querySelector() accepts any CSS selector and returns the first matching element, while getElementById() only searches by the id attribute, but is simpler.
- document.querySelector()Returns the first element that matches a CSS selector, or null when nothing matches.
- document.querySelectorAll()Returns a static list (NodeList) of every element that matches a CSS selector.
- Node.textContentReads or sets all of an element’s text, without HTML markup.
- EventTarget.addEventListener()Registers a function that’s called every time a given event occurs on an element, for example a click.
Spotted a mistake or missing an example? Write to us.