Dominik König
Dominik König

Reputation: 124

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.

Upvotes: 4

Views: 1324

Answers (2)

Dominik K&#246;nig
Dominik K&#246;nig

Reputation: 124

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

Upvotes: 3

ryanpcmcquen
ryanpcmcquen

Reputation: 6465

Use the :unresolved pseudo-selector along with the .constructor property:

var isUnresolved = function(selector) {
  var element = document.querySelector(selector + ':unresolved');
  try {
    return (/HTMLElement/).test(element.constructor);
  } catch (ignore) {
    return false;
  }
};
console.log(
  isUnresolved('foo-bar')
);
console.log(
  isUnresolved('main')
);
<foo-bar></foo-bar>
<main></main>

Upvotes: 0

Related Questions