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

Viewed 224
2 Answers

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.

You can try do it like this:

if (document.myElement.createShadowRoot || document.myElement.attachShadow) {
    // support shadow DOM
} else {
    // not support
}
Related