Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does "window = window.parent;" create an infinite loop?

Tags:

javascript

dom

I was traversing through a frame hierarchy, and tried the following to find the top frame:

var win = window;
while (win.parent) {
    //perform actions on win
    win = win.parent;
}

By now, I know that the correct looping condition must be:

while (win !== top) {

The existence check on win.parent seemingly creates an infinite loop. Is there any particular reason why it is like this? Why should top have a parent?

like image 540
Stefan Majewsky Avatar asked Mar 23 '12 10:03

Stefan Majewsky


2 Answers

You should also check if window.parent == window​ is false. Otherwise you will end up with an infinite loop. If there is no parent, the parent property will reference to itself (infinite loop).

var win = window;
while (win.parent && win.parent != win) {
    //perform actions on win
    win = win.parent;
}​

http://jsfiddle.net/EZfHf/

I found this on MDN:

If a window does not have a parent, its parent property is a reference to itself.

like image 122
Simon Edström Avatar answered Nov 11 '22 07:11

Simon Edström


top's parent is itself.

top == top.parent //true
like image 45
Madara's Ghost Avatar answered Nov 11 '22 09:11

Madara's Ghost