Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing elements of parent window from iframe (jquery)

I have several dinamically created divs, with the same elements inside:

<div id="(dinamic_id_1)">
    <div class="(element_1)">Some text here</div>
    <input class="(element_2)" />
    <iframe class="(element_3)" src="form.php?id=(dinamic_id_1)" />
</div>

<div id="(dinamic_id_2)">
    <div class="(element_1)">Some text here</div>
    <input class="(element_2)" />
    <iframe class="(element_3)" src="form.php?id=(dinamic_id_2)" />
</div>

...

And there's a form within the iframe that would look something like this:

<form id="(dinamic_id)" >
    <input class="(class_input)" />
</form>

And my jquery function:

$(".class_input").change(function() {
    $(this).closest("form").submit();
});

There are other actions that I want to execute on submit on the parent window, on the elements contained within the div that shares the same id as the form. I got to get the html within the parent div like this:

var parent_div = $("div#"+$(this).closest("form").attr("id"), parent.document);
alert($(parent_div).html());

But I can't get to the elements within the div, for example:

var parent_div = $("div#"+$(this).closest("form").attr("id"), parent.document);
alert($(parent_div+" .element_1").html());

or

var parent_div = $("div#"+$(this).closest("form").attr("id")+" .element_1", parent.document);
alert($(parent_div).html());

Return null instead of "Some text here".

like image 241
Sandra Avatar asked Feb 05 '12 12:02

Sandra


People also ask

Can an iframe access its parent?

When a page is running inside of an iframe, the parent object is different than the window object. You can still access parent from within an iframe even though you can't access anything useful on it. This code will never cause an error even when crossing origins.

How do I transfer data from iframe to parent?

Sending data from child iframe to parent window : Whenever you embed an iframe, the iframe will have a reference to the parent window. You just need to use the PostMessage API to send data via the window. parent reference of the parent window.

What is window parent?

The Window. parent property is a reference to the parent of the current window or subframe. If a window does not have a parent, its parent property is a reference to itself.


1 Answers

Try modifying the code to the following:

var parent_div = $("div#"+$(this).closest("form").attr("id"), parent.document);
alert(parent_div.children('.element_1').text());

I knocked up a quick test my end and all worked fine.

Edit: Explanation

The problem is that you were trying to reference parent_div as a string, when in fact it is a jQuery object on it's own.

alert($(parent_div + " .element_1").html());
//     ( [object]  +    [string]  )
like image 51
Goran Mottram Avatar answered Sep 20 '22 01:09

Goran Mottram