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.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.