最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论

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 0
Add a ment  | 

2 Answers 2

Reset to default 5

You 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

发布评论

评论列表(0)

  1. 暂无评论