简体   繁体   中英

Javascript : Looping through nested window object to find particular element

I have a nested object .How do I change it to while loop or for loop. So that I can handle it for multiple levels.

var myObj = {};
if (window.dialogArguments && window.dialogArguments.previousWindow) {

    if (window.dialogArguments.previousWindow.dialogArguments &&
        window.dialogArguments.previousWindow.dialogArguments.previousWindow) {

        //Continue traversing

    }

} else {
    //Do something like :
    myObj = window.document.body;
}

previousWindow is an property of one window object which again holds dialogArguments .

If I understand correctly, you want to keep stepping deeper into nested objects until you find a window without dialogArguments or dialogArguments.previousWindow .

You can loop on a variable that you continue to update with the deeper object until you find one that doesn't have any further depth:

var myObj = {};
var currentWindow = window;

while (currentWindow.dialogArguments && currentWindow.dialogArguments.previousWindow) {
  currentWindow = currentWindow.dialogArguments.previousWindow;
}
else {
  myObj = currentWindow.document.body;
}

If I understand it well, you can use

var win, tmp = win = window;
while(tmp = tmp.dialogArguments)
    if(tmp = tmp.previousWindow)
        win = tmp;
var myObj = win.document.body;

or

var win, tmp = win = window;
while((tmp = tmp.dialogArguments) && (tmp = tmp.previousWindow))
    win = tmp;
var myObj = win.document.body;

or

var win, tmp = window;
do{ win = tmp; }
while ((tmp = tmp.dialogArguments) && (tmp = tmp.previousWindow))
var myObj = win.document.body;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM