How to use document.getElementById() in TypeScript

avatar

Borislav Hadzhiev

Thu Mar 31 20222 min read

banner

Photo by JoelValve

How to use document.getElementById() in TypeScript #

To use the document.getElementById() method in TypeScript:

  1. Use a type assertion to type the selected element correctly.
  2. Use a type guard to make sure the variable does not store a null value.
  3. Access any element-specific properties.

This is the index.html file for the examples in this article.

index.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> </head> <body> <input id="message" type="text" name="message" value="Initial Value" /> <div id="box">hello world</div> <button id="btn">Submit</button> <script src="./src/index.ts"></script> </body> </html>

And here is the related TypeScript code.

src/index.ts
const input = document.getElementById('message') as HTMLInputElement | null; if (input != null) { console.log(input.value); // 👉️ "Initial Value" } // --------------------------------- const box = document.getElementById('box') as HTMLDivElement | null; console.log(box?.innerHTML); // 👉️ "hello world" // --------------------------------- const button = document.getElementById('btn') as HTMLButtonElement | null; if (button != null) { console.log(button.innerText); // 👉️ "Submit" }

The document.getElementById method has a return type of HTMLElement | null. If no element with the provided id exists in the DOM, the method returns a null value.

If we have to access any element-specific properties on the variable, we have to use a type assertion to type it correctly

Type assertions are used when we have information about the type of a value that TypeScript can't know about.

We effectively tell TypeScript that the input variable stores anHTMLInputElement or a null value and not to worry about it.

In the first example, we typed the input variable as HTMLInputElement | null.

The types are consistently named as HTML***Element. Once you start typing HTML.., your IDE should be able to help you with autocomplete.

Some commonly used types are: HTMLInputElement, HTMLButtonElement, HTMLAnchorElement, HTMLImageElement, HTMLTextAreaElement, HTMLSelectElement, etc.

We used a simple if statement as a type guard to make sure the input variable doesn't store a null value before accessing properties on it.

src/index.ts
const input = document.getElementById('message') as HTMLInputElement | null; // 👉️ input has type HTMLInputElement or null here if (input != null) { // 👉️ input has type HTMLInputElement here console.log(input.value); // 👉️ "Initial Value" }
TypeScript knows that the input variable has a type of HTMLInputElement in the if block and allows us to directly access its value property.

It's always a best practice to include null in the type assertion, because the getElementById method would return null if no element with the provided id was found.

You might also use the optional chaining (?.) operator to short-circuit if the reference is equal to null or undefined

src/index.ts
const box = document.getElementById('box') as HTMLDivElement | null; console.log(box?.innerHTML); // 👉️ "hello world"

The optional chaining operator short-circuits returning undefined if the reference is equal to null or undefined.

In other words, if the box variable stores a null value, we won't attempt to access the innerHTML property on null and get a runtime error.

If you don't use a type assertion with the document.getElementById method, the type of the variable is going to be HTMLElement | null.

src/index.ts
// 👇️ const input: HTMLElement | null const input = document.getElementById('message'); if (input != null) { // ⛔️ Can't access value here console.log(input.value); // 👉️ "Initial Value" }

Since the value property doesn't exist on the HTMLElement type, we aren't allowed to access it.

This approach is sufficient when you don't have to access any element-specific properties.

Use the search field on my Home Page to filter through my more than 1,000 articles.