0

I would like to know how to have my parent page reach into an iframe and set the innerhtml (using jQuery .html()) to a variable that I will supply.

Here is what I have so far:

var iframe = document.getElementById('framer');
var innerDoc = iframe.contentDocument || iframe.contentWindow.document;
var content_destination = innerDoc.getElementById('placecontenthere');  
$(content_destination).html("<span class='red'>Hello</span>");

Any thoughts?

fragilewindows
  • 1,394
  • 1
  • 15
  • 26

1 Answers1

1

For accessing iframe contents with jQuery you can use the contents() - function, as described here: http://api.jquery.com/contents/

Your code example could be replaced by a oneliner;

$('#framer').contents().find('#placecontenthere').html('<span class="red">Hello</span>');
nepumuk
  • 86
  • 6
  • Hi! I have seen that one line of code around a lot of questions like this one. After having tried lots of variations on that, none of them working, I am still stumped. –  May 23 '13 at 05:35
  • 1
    okay, then it might be useful to know, what exactly you are displaying inside the iframe. It seems to me that there's something wrong with your markup or that for some reason your browser does not allow access to this particular iframe (maybe because of same origin policy) – nepumuk May 23 '13 at 05:40
  • inside the iframe I have a pretty large php document with a lot of CSS, PHP, and Javascript. I was hoping to find a div inside of the iframe and place dynamic content in it. –  May 23 '13 at 05:43
  • also, I dont think i am in violation of the same origin policy. the parent page is a wordpress template, and the iframe src is a page in the same server, nearby in the directory structure and it loads fine enough. Is there a test though? To make sure they are registering as the same? –  May 23 '13 at 05:45
  • Sounds like it's okay. In my opinion there are two possible reasons left: Either #framer or #placecontenthere is not found by the jQuery selector engine. Can you verify that #placecontenthere exists inside your iframe? – nepumuk May 23 '13 at 05:51