document.getElementById
Returns an Element object representing the element whose id property matches the specified string
Syntax
document.getElementById(id)Parameters
| Parameter | Type | Description |
|---|---|---|
| id | string | The ID of the element to locate, case-sensitive |
Return Value
An Element object, or null if no element with the ID exists
Examples
const app = document.getElementById('app')
if (app) {
app.textContent = 'Hello World'
}const canvas = document.getElementById('myCanvas') as HTMLCanvasElement
const ctx = canvas?.getContext('2d')
if (ctx) ctx.fillRect(0, 0, 100, 100)function show(id: string) {
const el = document.getElementById(id)
if (el) el.style.display = 'block'
}Understanding document.getElementById
The document.getElementById method in JavaScript returns an Element object representing the element whose id property matches the specified string. It belongs to the Document object and is one of the most widely used methods for working with document values in modern JavaScript and TypeScript applications.
The method signature is document.getElementById(id). It accepts 1 parameter: id. When called, it returns an element object, or null if no element with the id exists. Understanding when and how to use getElementById() helps you write more expressive, readable code.
Common use cases for document.getElementById include data transformation, input validation, API response processing, and building reusable utility functions. It works well alongside related methods like dom-queryselector, dom-getelementsbyclassname, dom-getelementsbytagname, enabling you to chain operations together for complex data manipulation pipelines.
Browser support for document.getElementById is excellent across all modern browsers including Chrome, Firefox, Safari, and Edge. It is also fully supported in Node.js and Deno. For older environments, transpilation with Babel or a polyfill may be needed.
Browser Compatibility
Supported in all modern browsers (Chrome, Firefox, Safari, Edge) and Node.js. Part of the ECMAScript standard.
Related Methods
document.querySelectorReturns the first Element within the document that matches the specified CSS selector, or null if no matches are found
document.getElementsByClassNameReturns a live HTMLCollection of all child elements which have all of the given class names
document.getElementsByTagNameReturns a live HTMLCollection of elements with the given tag name
More Document Methods
Other methods in the Document object
Related Tools
More Document Methods
Explore JavaScript Methods
Browse our complete reference of 410 JavaScript methods with syntax, examples, and explanations.