JavaScript Reference ยท DOM: Document and Elements
document.getElementById()
Reference for getElementById(): find an element by its id attribute, handle null, avoid duplicate ids and named global variables, with live examples.
document.getElementById() returns the element whose id attribute equals the string you pass, or null if there is none. Ids are meant to be unique in a document, so the answer is a single element, not a list.
It is the oldest and simplest lookup method. It takes a plain id, not a selector: write "menu", not "#menu".
const menu = document.getElementById("menu"); menu.hidden = false;
Try it
Syntax
document.getElementById(id)
| Name | Description |
|---|---|
id |
The id to look for, as a string. Matching is case sensitive and uses the exact text, without a leading #. |
Return value: the first Element in the document with that id, or null.
Exceptions: none. An unknown id simply gives null.
Usage notes
- Only on documents (and document fragments). Regular elements do not have it; use
element.querySelector("#id")for scoped searches. - Only finds connected elements. An element you created but have not inserted into the document cannot be found by id.
- Keep ids unique. Duplicate ids are invalid HTML. The method returns the first match, which hides the problem and breaks things like
<label for>and fragment links. - Special characters are fine. Because the argument is not a selector,
getElementById("a.b")works without escaping, whilequerySelector("#a.b")would not. - Do not rely on named globals. Browsers also expose elements with an id as properties of
window, sostatusormenumay exist as a variable without declaring it. That feature is fragile (it can clash with real globals), so look elements up explicitly. - Handle
null. If the script runs before the element is parsed, you getnull. Place the script after the markup, usedefer, or wait forDOMContentLoaded. - Id, not name. It does not look at the
nameattribute. For form controls useform.elementsor a selector.
Browser support
Supported in every browser, including very old ones.