How to use document.getElementById() in TypeScript

avatar
Borislav Hadzhiev

Last updated: Feb 29, 2024
3 min

banner

# 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 doesn't store a null value.
  3. Access any element-specific properties.

This is the index.html file for the examples.

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" }

how to use document getelementbyid in typescript

The code for this article is available on GitHub

Here is an example of using document.getElementById() to select the div element.

index.ts
const box = document.getElementById( 'box', ) as HTMLDivElement | null; console.log(box?.innerHTML); // ๐Ÿ‘‰๏ธ "hello world"

using document get element by id to select the div

And here is an example that uses the method to select the button element.

index.ts
const button = document.getElementById( 'btn', ) as HTMLButtonElement | null; if (button != null) { console.log(button.innerText); // ๐Ÿ‘‰๏ธ "Submit" }

using the method to select the button element

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 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" }
The code for this article is available on GitHub
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.

# Using the optional chaining (?.) operator

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 code for this article is available on GitHub

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.

I've also written an article on how to use document.querySelector() in TypeScript.

If you need to get the value of an input element in TS, click on the link and follow the instructions.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev