Check if element contains #shadow-root

丶灬走出姿态 提交于 2019-12-23 07:00:48

问题


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?


回答1:


If you want to check whether or not a specific element is hosting a Shadow DOM element, you can do the following:

var el = document.querySelector('#some-element');
if (el.shadowRoot === root) {
    // Then it is hosting a Shadow DOM element
}

You can also get the Shadow DOM element, and then operate on it like a normal node:

var shadowEl = el.shadowRoot;
// And for example:
console.log(shadowEl.innerHTML);

Here is an example that works in the latest version of Chrome:

<p>A Normal Paragraph</p>
<div>A Normal Div</div>

<script>
    var host = document.querySelector('p');
    var root = host.createShadowRoot();
    root.textContent = 'A Shadow DOM Paragraph';

    // Let's go ahead and query it again so we can see this work in an actual scenario
    var p = document.querySelector('p');
    var div = document.querySelector('div');

    console.log('Paragraph has Shadow DOM:', (p.shadowRoot === root)); // true
    console.log('Div has Shadow DOM:', (div.shadowRoot === root)); // false
</script>

I gave you the strict method of checking the condition in all of these examples. You can of course do the following as well:

if (el.shadowRoot) {} //to loosely check
if (!!el.shadowRoot) {} //to force boolean



回答2:


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
    });


来源:https://stackoverflow.com/questions/35375240/check-if-element-contains-shadow-root

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!