2011-02-04 116 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是你會選擇