How to Select a DOM Element
A guide on how to select DOM elements in TypeScript using querySelector
and getElementById
, with a focus on getting the correct types for the elements.
When you need to work with HTML elements in TypeScript, you first need to select
them from the DOM. The most common ways are using document.querySelector
or
document.getElementById
.
It’s important to also tell TypeScript what kind of element you’re expecting, so you get the right type hints and prevent errors.
Here is a common setup: You have a button to open a search dialog.
<button id="open-search">Open Search</button>
<dialog id="search-box">
<h1>Dialog</h1>
</dialog>
<script>
document.addEventListener("DOMContentLoaded", () => {
// Your code here
});
</script>
To make this work, you need to select the <button>
and the <dialog>
.
You can use querySelector
with any CSS selector, like an ID, class, or tag
name. When you use it, you should tell TypeScript what kind of element to
expect.
const openSearchButton =
document.querySelector<HTMLButtonElement>("#open-search");
const searchBox = document.querySelector<HTMLDialogElement>("#search-box");
By adding <HTMLButtonElement>
and <HTMLDialogElement>
, you are telling
TypeScript “I expect this to be a button” or “I expect this to be a dialog”.
If the element might not exist, querySelector
will return null
. So you
should always check if you found it before using it.
if (openSearchButton && searchBox) {
openSearchButton.addEventListener("click", () => {
searchBox.showModal();
});
}
If you are selecting by ID, getElementById
is a good choice. It’s a bit
faster.
const openSearchButton = document.getElementById(
"open-search"
) as HTMLButtonElement | null;
const searchBox = document.getElementById(
"search-box"
) as HTMLDialogElement | null;
With getElementById
, TypeScript doesn’t know what kind of element it is, so
you have to use as
to tell it. This is called type casting.
Just like querySelector
, you need to check if the elements exist before using
them.