How to get HTMLElement from element with TypeScript?

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.