Detect if Element is a Web Component

By  on  

I've advocated for web components since before they became a spec, mostly inspired by the Dojo Toolkit's dijit framework. Empowering first class JavaScript widgets, as opposed to a mess of DIVs and templates, always made the most sense. Now that web components exist, and awesome frameworks like Ionic are based on them, I wanted to discover how to detect a web component, as opposed to a regular HTML element, with JavaScript. As it turns out, it's much easier than you'd think.

Assuming you have a reference to an element, it's as easy as detecting a dash in the element's tag:

function isWebComponent(element) {
  return element.tagName.includes("-");
}

The web component spec requires a dash in the HTMLElement's tagName, so detecting a web component is essentially nailed down to a string comparison.

If you haven't played with web components, I really hope you find the time. Having lived through decades of "widgets" and over-nesting of arbitrary DIVs and unreadable code, I've learned to appreciate these gems!

Recent Features

  • By
    Serving Fonts from CDN

    For maximum performance, we all know we must put our assets on CDN (another domain).  Along with those assets are custom web fonts.  Unfortunately custom web fonts via CDN (or any cross-domain font request) don't work in Firefox or Internet Explorer (correctly so, by spec) though...

  • By
    5 More HTML5 APIs You Didn’t Know Existed

    The HTML5 revolution has provided us some awesome JavaScript and HTML APIs.  Some are APIs we knew we've needed for years, others are cutting edge mobile and desktop helpers.  Regardless of API strength or purpose, anything to help us better do our job is a...

Incredible Demos

Discussion

  1. Wouldn’t that just check whether it is a custom element? To my knowledge, custom elements can live on their own and do not have to be actual web components.

    • Šime Vidas

      Could you explain the difference between a custom element and a web component?

    • Jv

      My exact thought, Catalin! This isn’t really robust enough..

  2. Yaisiel

    I feel like that will not work if you declare your web component as a “customized built-in” (https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_custom_elements#Customized_built-in_elements). That type of component is built on top of an existing element (like a for example) and the tag names don’t contain hyphens. I’m not sure, however, how many people would follow that approach in practice. It might be that, for the majority of the cases, checking for hyphens is enough.

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!