Check if the Home item is Native / no Custom Element

Is there a way to check if a Dom element is a Native element or a custom element (not allowed) without checking all proper tag names in Javascript?

I already thought about checking for element.constructor === HTMLElement, but the <main>( documentation ) tag has this as a top-level class.

Basically I need a faster and less intensive verification process for my own element.

+4
source share
2 answers

So, after the Supersharp comment , I found out that all user-defined tagName elements or the is attribute must contain a hyphen and never have to do their own elements, so the best way to use this function is:

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

Just like that.

W3C Documentation :

They contain a hyphen used for the namespace and for direct compatibility (since in the future elements will not be added to HTML, SVG or MathML with hyphenated local names).

+1
source

Use the pseudo selector :unresolvedalong with the property .constructor:

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>
Run codeHide result
0
source

Source: https://habr.com/ru/post/1674005/


All Articles