HTML DOM Document getElementById()
Example
Get the element with the specified id:
document.getElementById("demo");
Try it Yourself »
Get the element and change its color:
const myElement = document.getElementById("demo");
myElement.style.color = "red";
Try it Yourself »
Or just change its color:
document.getElementById("demo").style.color = "red";
Try it Yourself »
Description
The getElementById()
method returns an element with a specified value.
The getElementById()
method returns null
if the element does not exist.
The getElementById()
method is one of the most common methods in the HTML DOM.
It is used almost every time you want to read or edit an HTML element.
Note
Any id should be unique, but:
If two or more elements with the same id exist, getElementById()
returns the first.
See Also:
The getElementsByTagName() Method
Syntax
document.getElementById(elementID)
Parameters
Parameter | Description |
id | Required. The id value of an element. |
Return Value
Type | Description |
Object | The element with the specified id.null if the element does not exist. |
Related Pages:
CSS Tutorial: CSS Syntax
CSS Reference: CSS #id Selector
HTML DOM Reference: HTML DOM id Property
HTML DOM Reference: HTML DOM Style Object
Browser Support
document.getElementById()
is a DOM Level 1 (1998) feature.
It is fully supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | 9-11 |