Dave Teu Dave Teu - 7 months ago 7
Javascript Question

Append within Append, Iframe within Append in Jquery

I've looked at
Insert content into iFrame and their fiddle at http://jsfiddle.net/8VP4y/3/ to come out with the following codes which i'm having problem.

i've created a jsfiddle for my problem below.


https://jsfiddle.net/cy87j70t/2/


$( document ).ready(function() {

$('#card2').html( '<iframe id="myFrame"></iframe>' );

var myFrame = $("#myFrame").contents().find('body');
var myFrame2 = $("#myFrame2").contents().find('body');

myFrame.append('<p>OH NO TOKEN IS FOR myFrame Original ');
myFrame2.append('<p>OH NO TOKEN IS FOR myFrame 2 ');

});


AND the HTML looks like this;

<div id='card2'>

</div>
<iframe id='myFrame2'>

</iframe>


I'm trying to create a iframe using javascript, then writing to the iframe with content from JSONP (i've ommitted that part for easy debug);

I'm not sure why it's not writing to the iframe, is it because the iframe is created by javascript?

I've tried append, html, after, prepend but nothing seems to allow me to write to the iframe

Answer

No, it's not a bug.

Updated jsfiddle

The right way is:

$(function () {
  $('#card2').html('<iframe id="myFrame"></iframe>');

  // add the src attribute so that the load event will take place in every browser..
  $("#myFrame").attr('src', 'about:blank');

  // wait for the iframe is loaded
  $("#myFrame").on('load', function(e) {
    var myFrame = $("#myFrame").contents().find('body');
    myFrame.append('<p>11111111OH NO TOKEN IS FOR myFrame Original</p>');
  });



  var myFrame2 = $("#myFrame2").contents().find('body');
  myFrame2.append('<p>2222222222  OH NO TOKEN IS FOR myFrame 2</p>');
});
<script src="https://code.jquery.com/jquery-1.12.1.min.js"></script>

<div id='card2'>

</div>
<iframe id='myFrame2'>

</iframe>