Reputation: 14863
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.
Upvotes: 6
Views: 19952
Reputation: 2586
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.
Upvotes: 8
Reputation: 10404
TypeScript only provides type definitions for already existing objects, it can't modify the nature of the object. So, your question is about javascript and not about typescript.
Inside the lib.dom.d.ts
(the type definition library used by Angular), the MutationObserver
object is not much correctly defined:
interface MutationObserver {
disconnect(): void;
observe(target: Node, options: MutationObserverInit): void;
takeRecords(): MutationRecord[];
}
where target
is defined as Node
element.
HTMLElement
is defined inside the same file, and it extends Element
which extends Node
. So HTMLElement
shouldn't have any problem to fit inside the target property.
A better type definition would be:
observe<T extends Node>(target: T, options: MutationObserverInit): void;
But since this type definition hasn't been provided, it would be better if you tell the the compiler that it's perfectly fine just passing element as Node
inside the callback.
Upvotes: 3
Reputation: 1504
You can convert the HTML into a string and then convert the string with this method:
const stringHTML = '<div>One</div><div>Two</div>';
const fragment = document.createRange().createContextualFragment(stringHTML);
console.log(fragment);
Maybe this link will help: convert-html-stings-dom-nodes
There is also another method called DOM parser. It is explained in the link. Hope it helps.
Upvotes: 0