1

Index.html

 <li>
       <a href="#" id="run">Run</a>
 </li>
    <iframe id="outputContentLoadContainer" src="" style="border:none"></iframe>

output.html

<!DOCTYPE html>
<html lang="en">
<head> 
<style>
p{
   color: blue;
} 
</style>
</head>
<body>
<div id="container">
 <p>hi I am new html.</p>
</div>
</body>
</html>

JS:

   $("#run").click(function(e) {    
            $("#outputContentLoadContainer").attr("src","index_output.html");
        $("#outputContentLoadContainer").contents().find("body").append('<p>Test</p>');     

  }); 

On click of Run I am appending <p>Test</p> to body of iframe html but it's only showing <p>hi I am new html.</p> why?

Akki619
  • 2,386
  • 6
  • 26
  • 56
  • 1
    use $("#run").on('click',function(e) instead of $("#run").click(function(e) – Alok Deshwal Oct 23 '15 at 12:28
  • @AlokDeshwal they are the same thing, `click()` is simply a shortcut for `on('click'...` – charlietfl Oct 23 '15 at 12:34
  • @ charlietfl 2 No I think they are not same thing where ever i know .on method in jquery is used to bind the event where your html is created dynamically – Alok Deshwal Oct 23 '15 at 12:36
  • @AlokDeshwal the signature you provided does not do any delegation. That element must exist the way you have written it ... and yes`click()` uses `on()` internally so they are the same in this situation – charlietfl Oct 23 '15 at 12:39
  • @ charlietfl 29 Will you please check the following link http://stackoverflow.com/questions/9122078/difference-between-onclick-vs-click – Alok Deshwal Oct 23 '15 at 13:10

2 Answers2

1

Issue is no different than using document.ready to allow the dom to load before running code... you need to let the iframe load also.

Think of it as an asynchronous operation .. there is time involved in getting the new page and time needed to render it

Try:

 $("#outputContentLoadContainer").on('load', function(){    
     $(this).contents().find("body").append('<p>Test</p>');
});

$("#run").click(function(e) {    
      $("#outputContentLoadContainer").attr("src","index_output.html");
});

DEMO

charlietfl
  • 170,828
  • 13
  • 121
  • 150
0

Jquery selector takes in a second param as a document Object in your example it would be $('#outputContentLoadContainer').document

Inserting a P tag

$('body', $('#outputContentLoadContainer').document).on('load',function(){
     $(this).append('<p>My Text in Dynamic iframe</p>');
});
joyBlanks
  • 6,419
  • 1
  • 22
  • 47