Check if element contains #shadow-root

Chase picture Chase · Feb 13, 2016 · Viewed 10.5k times · Source

Is it possible to see if a Shadow DOM element exists? I'm not too concerned with manipulating it, or even really targeting it per-say. I understand the reasoning of the encapsulation. But I'd like to be able to style other elements in the regular DOM, based on whether or not the Shadow DOM element is present.

Sort of like:

if ( $('#element-id #shadow-root').length ) {
    // true
}

Or if not for the shadow-root, at least a specific element within, like the id of a div. So if that div exists, then clearly that Shadow DOM element is on the page.

I know it wouldn't be that simple... From some research I've done, there are things like >>> and /deep/ but their support seems to be low/none/deprecated. Buy maybe there's another way, however inelegant it may be?

Answer

Marko Kajzer picture Marko Kajzer · Feb 13, 2016

You can access the shadowRoot of an element with the property shadowRoot, so you could traverse all the nodes and check if the property is null or not.

You can select all nodes in a document with document.getElementsByTagName('*').

So all in all, we would have something like this:

var allNodes = document.getElementsByTagName('*');
for (var i = 0; i < allNodes.length; i++) {
  if(allNodes[i].shadowRoot) {
    // Do some CSS styling
  }
}

With the additions of ES6, we could do something simpler like this:

document.getElementsByTagName('*')
    .filter(element => element.shadowRoot)
    .forEach(element => {
        // Do some CSS styling
    });