Last updated: Feb 29, 2024
Reading timeยท3 min
To use the querySelector()
method in TypeScript:
null
value.This is the index.html
file for the examples.
<!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.
const input = document.querySelector('#message') as HTMLInputElement | null; if (input != null) { console.log(input.value); // ๐๏ธ "Initial value" }
Here is an example that uses the querySelector
method to select the div
by
class.
const box = document.querySelector('.box') as HTMLDivElement | null; console.log(box?.innerHTML); // ๐๏ธ Box 1
And here is an example that uses the method to select the button
by its
data-id
attribute.
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.
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
.
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.
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" }
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
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
.
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
.
// ๐๏ธ 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.
// ๐๏ธ 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've also written an article on how to use document.getElementById in TS.
You can learn more about the related topics by checking out the following tutorials: