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

  • See Supersharp's answer, customElements.get is clearly the better way to do this than the below.


    A custom element's name is required to contain a -, whereas an HTML-defined element will not. So:

    if (theElement.tagName.includes("-")) {
        // It's custom
    } else {
        // It isn't
    }
    

    (Or .indexOf("-") != -1 for older browsers that don't have String#includes yet.)