Categories
TypeScript Answers

How to get HTMLElement from element with TypeScript?

Spread the love

Sometimes, we want to get HTMLElement from element with TypeScript.

In this article, we’ll look at how to get HTMLElement from element with TypeScript.

How to get HTMLElement from element with TypeScript?

To get HTMLElement from element with TypeScript, we can cast elements to HTMLElement.

For instance, we write

const nodes = document.querySelectorAll<HTMLElement>("a");

to cast the items in the node list returned by querySelectorAll to HTMLElement.

We can also cast them to more specific element types with

const nodes = document.querySelectorAll<HTMLAnchorElement>("a");

to cast all the elements in the node list to the HTMLAnchorElement type.

Conclusion

To get HTMLElement from element with TypeScript, we can cast elements to HTMLElement.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *