jQuery select element in parent window

JqueryJquery SelectorsPopupParent

Jquery Problem Overview


Is there a way to select a DIV in the parent window using jQuery?

For example:

Main page contains this,

<div id="testdiv"></div>

Popup page has a form with some options and an 'Apply' button. When the user clicks apply it affects the style attribute on the main page.

Something along the logic of,

parent.$("#testdiv").attr("style", content from form);

Jquery Solutions


Solution 1 - Jquery

Use the context-parameter

$("#testdiv",parent.document)

But if you really use a popup, you need to access opener instead of parent

$("#testdiv",opener.document)

Solution 2 - Jquery

I looked for a solution to this problem, and came across the present page. I implemented the above solution:

$("#testdiv",opener.document) //doesn't work

But it doesn't work. Maybe it did work in previous jQuery versions, but it doesn't seem to work now.

I found this working solution on another stackoverflow page: https://stackoverflow.com/questions/2167455/how-to-access-parent-window-object-using-jquery

From which I got this working solution:

window.opener.$("#testdiv") //This works.

Solution 3 - Jquery

I came across the same problem but, as stated above, the accepted solution did not work for me.

If you're inside a frame or iframe element, an alternative solution is to use

window.parent.$('#testdiv');

Here's a quick explanation of the differences between window.opener, window.parent and window.top:

  • window.opener refers to the window that called window.open( ... ) to open the window from which it's called
  • window.parent refers to the parent of a window in a frame or iframe element

Solution 4 - Jquery

You can also use,

parent.jQuery("#testdiv").attr("style", content from form);

Solution 5 - Jquery

why not both to be sure?

if(opener.document){
  $("#testdiv",opener.document).doStuff();
}else{
  $("#testdiv",window.opener).doStuff();
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRobView Question on Stackoverflow
Solution 1 - JqueryDr.MolleView Answer on Stackoverflow
Solution 2 - JqueryTARKUSView Answer on Stackoverflow
Solution 3 - JquerycrodriguezView Answer on Stackoverflow
Solution 4 - JqueryJashwantView Answer on Stackoverflow
Solution 5 - JqueryThomas SmartView Answer on Stackoverflow