Document

document.getElementById

Returns an Element object representing the element whose id property matches the specified string

Syntax

JavaScript
document.getElementById(id)

Parameters

ParameterTypeDescription
idstringThe ID of the element to locate, case-sensitive

Return Value

An Element object, or null if no element with the ID exists

Examples

Basic Usage
const app = document.getElementById('app')
if (app) {
  app.textContent = 'Hello World'
}
Practical Example
const canvas = document.getElementById('myCanvas') as HTMLCanvasElement
const ctx = canvas?.getContext('2d')
if (ctx) ctx.fillRect(0, 0, 100, 100)
Advanced Usage
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

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.