31

Is there a way to manipulate the HTML of an iframe that is from the same domain using jQuery?

Thanks for the help.

Stephen Ou
  • 343
  • 1
  • 3
  • 5

4 Answers4

25

You'll have to parse the iframe content.

$("#frameid").contents().find("div").html('My html');

More here : http://api.jquery.com/contents/

c0mm0n
  • 969
  • 6
  • 6
  • 2
    Doesn't seem to work for some reasons. My code ` ` And the iframe: `
    `
    – Stephen Ou May 08 '11 at 03:45
  • 3
    @Stephen Ou: I'm a bit confused as to why this answer has +5 and mine has 0 despite providing exactly the same solution, but anyway... you're not actually doing anything with the HTML in that snippet you posted. If you want to set the HTML of your div, you need to pass a string to the `html()` function, eg: `html("new HTML")`. What you're doing in your snippet is getting the HTML of the div (which is empty anyway) and not doing anything with it. – Town May 08 '11 at 08:39
23

You can use contents() to manipulate the contents of the iframe.

$("#frameDemo").contents().find("div").html("new HTML content goes here");
Town
  • 14,706
  • 3
  • 48
  • 72
7

Here is an example from the jQuery documentation:

<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <iframe src="http://api.jquery.com/" width="80%" height="600" id='frameDemo'></iframe> 
<script>$("#frameDemo").contents().find("a").css("background-color","#BADA55");</script>

</body>
</html>
eldarerathis
  • 35,455
  • 10
  • 90
  • 93
Shahin
  • 12,543
  • 39
  • 127
  • 205
5

If you want to change the contents inside the <body> tag of the iframe, you can use this code:

$("#iframe_id").contents().find("body").html('my_new_content');
shasi kanth
  • 6,987
  • 24
  • 106
  • 158