7

I need to know if the document element is the ROOT node of the page. For example:

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

Javascript that is executed in iframe 1 or 2 should know if their document node is the root node.

Hope you can help me.

Van Coding
  • 24,244
  • 24
  • 88
  • 132

5 Answers5

14

You should be able to do this with top:

if (window.top.document === window.document) {
    // we're in the outermost window
}
lonesomeday
  • 233,373
  • 50
  • 316
  • 318
  • +1, but `top.document === window.document` is sufficient, `window.top` is just a slower way of doing `top` – Martin Jespersen Feb 04 '11 at 09:22
  • @Martin True, but I prefer to be explicit. I can imagine a circumstance where I would name a variable `top`. – lonesomeday Feb 04 '11 at 15:32
  • Well you could try, but in most browsers tho, if you try to assign a value to `top` it will either be ignored or throw an error. Besides, window is just a pseudo object that points to the global namespace of that frame, so being explicit as you call it, is just taking the long way around, sort of like sightseeing instead of using the freeway. – Martin Jespersen Feb 04 '11 at 20:45
  • @Martin Only if you try setting `top` as a global. If you set it with `var top` inside a function, it works fine. – lonesomeday Feb 04 '11 at 21:13
  • Very true, and good point. I'd probably never use a variable with that name myself (I don't think I have once in my 14 years of coding js), but others might, so it's good advise :) – Martin Jespersen Feb 04 '11 at 21:16
0

I suspect that, given the contents of an are different documents, they'll all report back as the root node. You might be better to check to see if document.parent is null or not.

Moo-Juice
  • 38,257
  • 10
  • 78
  • 128
0
if (window == window.parent) {
   alert("I'm not in a frame");
}
RoToRa
  • 37,635
  • 12
  • 69
  • 105
0

Make a function in your top document that returns it's rootNode, then call this function from your iframe documents by using the window.top reference:

in your top document:

function getRootNode()
{
 //returns the rootNode
}

In your iframe documents:

var rootNode = window.top.document.getRootNode();
Bazzz
  • 26,427
  • 12
  • 52
  • 69
0

try out this :

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

// where currentnode is the node which you'll select

Prakash
  • 6,562
  • 3
  • 25
  • 33