How to use querySelector with TypeScript
Are you getting crazy amount of errors on TypeScript when you’re using document.querySelector
?
property value does not exist on type Element
In today’s short article, I will go over how to properly define, and use your document.querySelector
with TypeScript.
The solution
In this code example, I’m going to create an h1
element, and I’m going to select the element with TypeScript.
<h1 class="headline">Hello World</h1>
const headline: HTMLHeadingElement | null = document.querySelector('.headline');
Let’s go over it really quickly.
I’ve created a variable named headline
and it has a type of HTMLHeadingElement
or null
. That’s because querySelector
may return the element if it exists. If it does not exist it will return a null
value.
Here are more examples with other HTML elements:
<p class="description">Hello World</p>
<div class="box"></div>
// Paragraph element
const desc: HTMLParagraphElement | null = document.querySelector('.description');
// Div element
const box: HTMLDivElement | null = document.querySelector('.box');
I like to tweet about code and post helpful code snippets. Follow me there if you would like some too!