问题
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