The JavaScript getElementById() method
The getElementById() method returns the element with a given id, or null if none has it. document.getElementById("header") finds the element with id="header". Pass the id without a #. It's fast and clear, though querySelector() is more flexible.
Overview
getElementById() is the original, no-frills element lookup: give it an id and it hands back that one element. It's called on document only, and you pass the id as a plain string with no # in front — getElementById("nav"), not getElementById("#nav"). That trips people up coming from CSS or querySelector().
If no element has that id, it returns null, so the same "check before you use it" rule applies as with querySelector(). Since an id is supposed to be unique on the page, it only ever returns a single element — there's no "all" version.
So which to use, this or querySelector("#id")? Both work. getElementById() is a touch faster and very readable for the common ID case, while querySelector() wins when your target needs a more complex selector. Many modern codebases just use querySelector() everywhere for consistency, which is a perfectly reasonable choice.
Syntax
const el = document.getElementById(id)
document.getElementById("header") // no '#'
Parameters
The getElementById() method accepts the following parameters.
| Parameter | Description |
|---|---|
id |
The id of the element to find, as a string with no leading #. |
Example
<p id="status">Waiting...</p>
<script>
const status = document.getElementById('status');
status.textContent = 'Ready!';
status.style.color = '#16a34a';
</script>
Best practices
- Pass the id without a
#— that prefix is for CSS selectors, notgetElementById(). - Check for
nullbefore using the result, in case the id isn't on the page. - Keep ids unique; duplicate ids are invalid and only the first is returned.
- Use querySelector() when you need a more complex selector than a plain id.
Frequently asked questions
Do I include the # in getElementById()?
getElementById("nav"). The # is only for CSS selectors and querySelector().What does getElementById() return if the id is not found?
null. Check the result before using it to avoid a "null" error.What is the difference between getElementById() and querySelector()?
getElementById() looks up by id only and is slightly faster; querySelector() accepts any CSS selector and is more flexible.