Search code examples
javascripttypescripthtmlelements

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.


Solution

  • 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.