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;
}
您可以只使用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.org/en-US/docs/Web/API/Node/getRootNode
Quick note : Currently it's not supported by IE/Edge
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.