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;
}
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./rudik/4/edit
Share Improve this question asked Jul 4, 2014 at 17:06 tomalectomalec 90011 silver badges27 bronze badges 02 Answers
Reset to default 5You can just use ownerDocument
:
element.ownerDocument;
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/en-US/docs/Web/API/Node/getRootNode
Quick note : Currently it's not supported by IE/Edge