检查 Dom 元素是否为原生/无自定义元素

Check if Dom Element is Native / no Custom Element

有没有办法在不检查 Javascript 中的所有原生标记名称的情况下检查 Dom 元素是原生元素还是(未解析的)自定义元素?

我已经考虑检查 element.constructor === HTMLElement,但是 <main> (documentation) 标签有这个,因为它是顶级 class。

基本上,我需要一种更快、更少维护的方式来检查原生元素。

使用 :unresolved 伪选择器和 .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>

所以在 之后,我发现所有自定义元素 tagName 或 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;
}

就这么简单。

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