Search code examples
javascriptweb-componentshadow-domcustom-element

How can i check whether an element can host Shadow DOM?


Elements that allow Shadow DOM are specified here: https://docs.w3cub.com/dom/element/attachshadow/

How can i validate if an element supports Shadow DOM or not ?

if (myElement.attachShadow) {
    ...
}

does not seem to work.


Solution

  • You could try and catch if unsupported.

    try {
       let shadowRoot = elem.attachShadow( { mode: "open" } );
       shadowRoot.innerHTML = ...;
       return true;
    } catch( err ) {
       return false;
    }
    

    You could also turn this into a helper, but if you need to use it several times, it might then be a good idea to store the results after checking each element.

    function canAttachShadow( elem ) {
      try {
        elem.cloneNode().attachShadow( { mode: "open" } );
        return true;
      }
      catch( err ) {
        return false;
      }
    }
      
    console.log( "a", canAttachShadow( document.createElement( "a" ) ) );
    console.log( "article", canAttachShadow( document.createElement( "article" ) ) );

    If you really wish, you could also use the specs algorithm, which is a combination of valid-custom-element-name and the white list in your article (i.e today, "article", "aside", "blockquote", "body", "div", "footer", "h1", "h2", "h3", "h4", "h5", "h6", "header", "main", "nav", "p", "section", or "span"), however this white list may change in the future, so any code using it would need to get updated along with the specs.