Check if element contains #shadow-root
If you want to check whether or not a specific element is hosting an open Shadow DOM element, you can do the following:
var el = document.querySelector('#some-element');
if (!!el.shadowRoot) {
// Then it is hosting an OPEN 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:
const div = document.querySelector('div');
const p = document.querySelector('p');
const shadowRoot = p.attachShadow({mode: 'open'})
shadowRoot.textContent = 'A Shadow DOM Paragraph. I overrode the content specified!';
console.log('Paragraph has Shadow DOM:', !!p.shadowRoot); // true
console.log('Div has Shadow DOM:', !!div.shadowRoot); // false
<div>A Normal Div</div>
<p>A Normal Paragraph</p>
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
});