Search code examples
javascriptweb-componentcustom-element

Check if Dom Element is Native / no Custom Element


Is there a way to check whether a Dom Element is a Native Element or a (not resolved) Custom Element without checking all Native tagNames in Javascript?

I Already thought of checking on element.constructor === HTMLElement but the <main> (documentation) tag has that as it's top level class.

Basically I need a faster and less maintenance intensive way of checking for a native element.


Solution

  • So after the comment of Supersharp I found out that all custom elements tagName or the is attribute must contain a hyphen and native elements never do, so the best way to figure that out is to use this function:

    function isCustomElement(element){
        if(element.tagName.indexOf("-") !== -1) {
            return true;
        }
        let isAttribute = element.getAttribute("is");
        if(isAttribute === null) {
            return false;
        }
        return isAttribute.indexOf("-") !== -1;
    }
    

    Simple as that.

    The W3C Standard documentation:

    They contain a hyphen, used for namespacing and to ensure forward compatibility (since no elements will be added to HTML, SVG, or MathML with hyphen-containing local names in the future).