AnonymousJan 04, 2024
To use the document.querySelector()
method in TypeScript, you can follow these steps:
Here is an example of how to use the document.querySelector()
method in TypeScript:
TypeScript
const myDiv = document.querySelector('#myId') as HTMLInputElement | null;
console.log(myDiv.innerHTML);
We are choosing an input element with the ID in this example. To inform TypeScript that the element being selected is an HTMLInputElement, we utilise a type assertion. In order to ensure that the input variable is not null before accessing its properties, we additionally employ a type guard.
You can also use the document.querySelector()
method to select elements by class . Here are some examples:
TypeScript
const myDiv = document.querySelector('.myClass') as HTMLDivElement | null;
console.log(myDiv.innerHTML);