Search code examples
javascriptweb-componentshadow-dom

What is the best way to find root node of elements DOM (shadow or light)


I would like to find the DOM scope of given element. In other words document or document fragment that contains it.

Is there anything nicer / faster than than code below?

function getRootNode( element ){
  if( document.contains(element) ){
    return document;
  }

  var root = element;
  while( root.parentNode ){
    root = root.parentNode;
  }
  return root;
}

http://jsbin.com/rudik/4/edit


Solution

  • Node.getRootNode() is the best way to do that in shadow dom it'll return the shadow root otherwise it'll return the document. See : https://developer.mozilla.org/en-US/docs/Web/API/Node/getRootNode

    Quick note : Currently it's not supported by IE/Edge