How To Copy Iframe Content To Div?
See code snippet below. I want the output text in the iframe to show in the #source div. I’m struggeling with this, and am grateful for any ideas. How can I copy the output text
Solution 1:
Keeping in mind that your iframe is on the same domain as your page:
// Get your iframe elementvar iframe = document.getElementById('iframe');
// Access contents of it like thisvar iframeContent = iframe.contentWindow.document;
// Get your div elementvar content = document.getElementById('source');
// set contents of this div to iframe's content
content.innerHTML = iframeContent.innerHTML;
Depending on when you're doing this, it also might be worth to wait till the iframe loads:
iframe.onload = function() { /* put the above code here */ }
Solution 2:
Further your comment:
A better solution to get a content from file is to use ajax.
Here is a simple approach of using ajax with jQuery.
$.ajax({
url: 'http://output.jsbin.com/sebusu',
success: function(data) {
$('#source').html(data);
$('#show').text(function(){
if (data.indexOf('Text') != -1) {
return'Can see text!';
}
else {
return"Can't see text!";
}
});
},
error: function(){
console.log(error);
}
});
<divid="source"></div><divid="show"></div><scriptsrc="https://code.jquery.com/jquery-3.1.0.js"></script>
Again, you can call ajax only for your website (with some exceptions)
Solution 3:
$("#my_iframe").on('load', function() {
$("#my_div").empty().append($('#my_iframe').contents().find('body').html());
});
Note: 'body' can be anything inside the iframe, if you want only a particular div, you can do '#div_inside_iframe' instead of 'body' using 'body' or 'html' will copy everything inside the iframe into the destination div.
Post a Comment for "How To Copy Iframe Content To Div?"