简体   繁体   中英

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.

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 (ie 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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM