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?

5
  • 1
    use $("#run").on('click',function(e) instead of $("#run").click(function(e) Commented Oct 23, 2015 at 12:28
  • @AlokDeshwal they are the same thing, click() is simply a shortcut for on('click'... Commented Oct 23, 2015 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 Commented Oct 23, 2015 at 12:36
  • @AlokDeshwal the signature you provided does not do any delegation. That element must exist the way you have written it ... and yesclick() uses on() internally so they are the same in this situation Commented Oct 23, 2015 at 12:39
  • @ charlietfl 29 Will you please check the following link stackoverflow.com/questions/9122078/… Commented Oct 23, 2015 at 13:10

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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>');
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.