How to use the querySelector() method in TypeScript

avatar

Borislav Hadzhiev

Last updated: Apr 1, 2022

banner

Photo from Unsplash

Use the querySelector() method in TypeScript #

To use the querySelector() 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" name="message" type="text" value="Initial Value" /> <div class="box">Box 1</div> <div class="box">Box 1</div> <button data-id="btn">Click</button> <script src="./src/index.ts"></script> </body> </html>

And here is the related TypeScript code.

src/index.ts
const input = document.querySelector('#message') as HTMLInputElement | null; if (input != null) { console.log(input.value); // 👉️ "Initial value" } // ------------------------------------------------------------- const box = document.querySelector('.box') as HTMLDivElement | null; console.log(box?.innerHTML); // 👉️ Box 1 // ------------------------------------------------------------- const button = document.querySelector( '[data-id="btn"]', ) as HTMLButtonElement | null; if (button != null) { console.log(button.innerText); // 👉️ "Click" }

The querySelector method has a return type of Element | null. If no element with the provided selector 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.querySelector('#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 querySelector method would return null if no element with the provided selector 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.querySelector('.box') as HTMLDivElement | null; console.log(box?.innerHTML); // 👉️ Box 1

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.querySelector method, the type of the variable is going to be Element | null.

src/index.ts
// 👇️ const button: Element | null const button = document.querySelector('[data-id="btn"]'); if (button != null) { // ⛔️ Can't access innerText here console.log(button.innerText); }

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

If you don't want to type the variable as a specific element, you can use the more broad HTMLElement type.

src/index.ts
// 👇️ const button: HTMLElement | null const button = document.querySelector('[data-id="btn"]') as HTMLElement | null; if (button != null) { console.log(button.innerText); }

The HTMLElement type has a bit more properties than the Element type. For example, the HTMLElement interface exposes properties like innerText, style, etc.

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.