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

The getElementsByClassName() Method

The querySelector() Method

The querySelectorAll() Method



Syntax

document.getElementById(elementID)

Parameters

Parameter Description
id Required.
The id value of an element.

Return Value

Type Description
ObjectThe 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 2 (2001) feature.

It is fully supported in all browsers:

Chrome Edge Firefox Safari Opera IE
Yes Yes Yes Yes Yes 9-11


Copyright 1999-2023 by Refsnes Data. All Rights Reserved.