2011-02-04 121 views
6

我需要知道文档元素是否为页面的ROOT节点。例如:检查文档是否为ROOT节点

<html> <-- ROOT Node 
    <head></head> 
    <body> 
     <iframe> 
     <html>...</html> <-- other document 
     </iframe> 
     <iframe> 
     <html>...</html> <-- other document 
     </iframe> 
    </body> 
</html> 

在iframe 1或2中执行的Javascript应该知道它们的文档节点是否是根节点。

希望你能帮助我。

回答

11

你应该能够top做到这一点:

if (window.top.document === window.document) { 
    // we're in the outermost window 
} 
+0

+1节点,但`top.document ===窗口.document`已经足够,`window.top`只是一个较慢的方法来做'top' – 2011-02-04 09:22:30

0

我怀疑,鉴于一个是不同的文件的内容,他们都会报告回作为根节点。您最好查看document.parent是否为空。

0
if (window == window.parent) { 
    alert("I'm not in a frame"); 
} 
0

让您的顶级文档中的函数,它返回它的根节点,然后在自己的iframe的文档调用此函数使用window.top参考:

的顶部文档中:

function getRootNode() 
{ 
//returns the rootNode 
} 

我n您的IFRAME文件:

var rootNode = window.top.document.getRootNode(); 
0

试试这个:

if(currentnode.parentNode == null) { alert("is root node") } 

//其中currentnode是你会选择