javascriptweb-componentcustom-element

Detect if dom element is custom web component or html element


In the given html, how can I tell that a dom element is a standard html component defined by the browser or a web component defined in a script (by an author):

<div></div>
<custom-web-component></custom-web-component>

I know that there is no way to check programmatically if a web component was already registered. Also they are both considered HTMLElement. Is there a way to check that a dom node is standard html or custom web component? Let's asume I get the dom element using querySelector()


Solution

  • To detect if a DOM element is a registred Custom Element, you should use customElements.get().

    If the element is not yet registered or if it's a standard HTML element, the method will return undefined.

    If it's a registered Custom Element it will return its class.

    customElements.define( 'custom-element', class extends HTMLElement {} )
    
    console.log( customElements.get( 'custom-element' ) )
    console.log( customElements.get( 'p' ) )
    console.log( customElements.get( 'fake-element' ) )
    console.log( customElements.get( 'font-face' ) )
    <custom-element></custom-element>
    <fake-element></fake-element>
    <p></p>
    <font-face></font-face>