Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Append element from iframe to it's body parent window.

I have elm.appendTo('#wrap');

where elm is a jquery object of the clicked image inside iframe. I want to append that image to a <div id="wrap"> where #wrap is a div in the body of the page outside iframe. So basically when i double click on an image inside iframe, i want that image to append to <body> outside iframe. Both body and iframe link are on the same domain.

like image 981
Pinkie Avatar asked Oct 03 '11 19:10

Pinkie


2 Answers

Provided that the frame and its parent are at the same domain. See SOP


Execute either of the following lines from within the iframe (parent can be replaced by top, if the parent document is in the top window):
//If the parent document doesn't have JQuery:
elm.appendTo(parent.document.getElementById("wrap"));

//Only if JQuery is included at the parent
elm.appendTo(parent.$("#wrap"));
parent.$("#wrap").append(elm);


If you want to grab the element inside the frame, from the context of the parent, use either of the following:

Assume #elm to be the ID of your image.

// If JQuery is defined at the frame AND the parent (current document)
$("#wrap").append(frames[0].$("#elm"));
frames[0].$("#elm").appendTo($("#wrap"));

frames[0] refers to the first frame within the current document. If you've set a name attribute on your frame, you can also use frames.frame_name, or frames["frame_name"].


Final example: Adding a click event listener to the elm JQuery (image) object:
elm.click(function(){
    parent.$("#wrap").append(this);
})
like image 167
Rob W Avatar answered Nov 05 '22 09:11

Rob W


Try going at it from the other way: from the parent window, find the element you want to append to and then use .append() and select the element in the iframe. For example:

$("#wrap").append($("iframe #myElement"));
like image 40
jtfairbank Avatar answered Nov 05 '22 09:11

jtfairbank