#webdevelopment
#coding
#queryselector method
#typescript

How can I use document.querySelector() method in TypeScript

Anonymous

AnonymousJan 04, 2024

To use the document.querySelector() method in TypeScript, you can follow these steps:

  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.

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);

Happy Coding! ❤️