Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript: Convert HTMLElement to Node

How can I convert a HTMLElement to a Node element.

According to this answer (https://stackoverflow.com/a/9979779/639035 ) a An element is one specific type of node... but I cannot find a way to convert them.

I specifically need a Node element, to pass it into a MutationObserver (https://nitayneeman.com/posts/listening-to-dom-changes-using-mutationobserver-in-angular/ ), and a HTMLElement throws an error.

like image 264
Stefan Avatar asked Sep 09 '26 00:09

Stefan


1 Answers

The best way to do this would be to cast your HTMLElement as a Node. There are two ways to do this. The first is the as syntax.

let myNode = theHTMLElement as Node;

You can also use the <> syntax.

let myNode = <Node>theHTMLElement;

Note: This changes the type when TypeScript is compiling, but does not magically give you the JS methods and properties of a Node.

It essentially allows you to bypass the type safety when you know you can. TypeScript will do its best to warn you if types are incompatible, but you can still introduce bugs if you are not careful.

like image 51
Daniel Morell Avatar answered Sep 10 '26 14:09

Daniel Morell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!