Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing div in iframe using Jquery

I have a "Page A". In this page is an iframe which displays "Page B".

<iframe id="iframeD" src="https://trello.com" width="600" height="600">
  <p>Your browser does not support iframes.</p>
</iframe>
<div id="cTitle">Hello</div>​

(See the following fiddle for a working example: http://jsfiddle.net/noscirre/yYkUN/)

"Page B" contains a div with id landingHeader. How can I create a jQuery call on "Page A" replace this div with another div (whose content is found on "Page A") with id cTitle?

like image 911
user1038814 Avatar asked Jan 31 '26 07:01

user1038814


2 Answers

 $("iframe").contents().find("#dTitle").attr('id','cTitle').html($('#cTitle').html());
like image 109
Anoop Avatar answered Feb 01 '26 22:02

Anoop


Assuming you're not violating the same origin policy,

1, Give your iframe an id - <iframe id="frm" src="javascript:undefined;"></iframe>​
2, Get the Window and HTMLDocument from the frame

var iWin = document.getElementById('frm').contentWindow,  
    iDoc = iWin.document;

3, Ceck for existance of jQuery in iframe

if( ! iWin.$ ){
    var jq = iDoc.createElement('script');
    jq.type = 'text/javascript';
    jq.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js';
    jq.onload = ready;
    iDoc.head.appendChild(jq);
}else{
    ready(); // the stuff you want to do
}

4, Do what you want with jQuery

function ready(){
    var div = iWin['$']('#frm_div')[0]; // example from fiddle
    div.textContent = 'bar';
}​

See this fiddle.

like image 21
Paul S. Avatar answered Feb 01 '26 21:02

Paul S.