53

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);
Keavon
  • 6,837
  • 9
  • 51
  • 79
Rob
  • 1,089
  • 3
  • 11
  • 19
  • possible duplicate of [how to access parent window object using jquery?](http://stackoverflow.com/questions/2167455/how-to-access-parent-window-object-using-jquery) – Dude Pascalou Jun 16 '15 at 16:00

5 Answers5

121

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)
Dr.Molle
  • 116,463
  • 16
  • 195
  • 201
23

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: how to access parent window object using jquery?

From which I got this working solution:

window.opener.$("#testdiv") //This works.
Community
  • 1
  • 1
TARKUS
  • 2,170
  • 5
  • 34
  • 52
4

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
Community
  • 1
  • 1
crodriguez
  • 193
  • 1
  • 2
  • 9
2

You can also use,

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

Jashwant
  • 28,410
  • 16
  • 70
  • 105
1

why not both to be sure?

if(opener.document){
  $("#testdiv",opener.document).doStuff();
}else{
  $("#testdiv",window.opener).doStuff();
}
Thomas Smart
  • 386
  • 3
  • 10