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 »
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.
Any id should be unique, but:
If two or more elements with the same id exist, getElementById()
returns the first.
The getElementsByTagName() Method
document.getElementById(
elementID)
Parameter | Description |
id | Required. The id value of an element. |
Type | Description |
Object | The element with the specified id.null if the element does not exist. |
CSS Tutorial: CSS Syntax
CSS Reference: CSS #id Selector
HTML DOM Reference: HTML DOM id Property
HTML DOM Reference: HTML DOM Style Object
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 |
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!