kofifus
kofifus

Reputation: 19295

check if element is the root document inside shadow dom

How can I check if for an element inside a shadow DOM, the element itself is the shadow root ?

I tried if (elem===elem.getRootNode()) but this doesn't work, as one is an element and one is a Node.

What is the correct test ?

My case is that I have code a Chrome extension that climbs up the DOM tree from a given element doing elem = elem.parentElement until elem===document.documentElement.

I am now trying to extend the above test condition to work for elements inside shadow DOM. When climbing up from an element in a shadow DOM I want to end when reaching the root of the shadow DOM not the root of the entire page.

I only need a Chrome solution.

Upvotes: 3

Views: 2893

Answers (1)

Techniv
Techniv

Reputation: 1967

elem.getRootNode() return the root Node of an element. So if you are in a Shadow DOM, elem.getRootNode() return the ShadowRoot node of the element.

You can simply check if an element is a ShadowRoot by the type of the element.

elem instanceof ShadowRoot

Here an exemple with a function that search the root. Useless because there is getRootNode, just for demo.

function findShadowRoot(element){
  if(element instanceof ShadowRoot) return element;
  if(!element.parentNode) return null;
  return findShadowRoot(element.parentNode);
}

var shadow = document.querySelector('#element-hote').attachShadow({mode: "open"});
shadow.innerHTML = '<p><span id="inner">Inner shadow text!</span></p>';
var inner = shadow.querySelector('#inner');
console.dir(inner.getRootNode().innerHTML)
console.dir(findShadowRoot(inner).innerHTML);
console.log(inner.getRootNode() == findShadowRoot(inner))
<html>
  <head></head>
  <body>
    <p id="element-hote"></p>
  </body>
</html>

Upvotes: 4

Related Questions