How to use document.querySelector() method in TypeScript

avatar
Borislav Hadzhiev

Last updated: Feb 29, 2024
3 min

banner

# Using the document.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 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" 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" }

using document queryselector method in typescript

The code for this article is available on GitHub

Here is an example that uses the querySelector method to select the div by class.

index.ts
const box = document.querySelector('.box') as HTMLDivElement | null; console.log(box?.innerHTML); // ๐Ÿ‘‰๏ธ Box 1

using query selector method to select div by class

And here is an example that uses the method to select the button by its data-id attribute.

index.ts
const button = document.querySelector( '[data-id="btn"]', ) as HTMLButtonElement | null; if (button != null) { console.log(button.innerText); // ๐Ÿ‘‰๏ธ "Click" }

using the method to select the button by its data id

The code for this article is available on GitHub

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 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.

# Make sure the element exists before accessing properties

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

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

I've also written an article on how to use document.getElementById in TS.

# 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