How to insert HTML content into an iFrame with jQuery
In this tutorial, we are going to see How to insert HTML content into an iFrame with jQuery. You can simply use the contents() method of jQuery in combination with the find(), val() and html() methods to insert text or HTML into the body of “iframe”.
How to insert HTML content into an iFrame with jQuery
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert HTML content into an iFrame with jQuery</title> <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script> <script type="text/javascript"> function addToframe(){ var frame = $("#frame").contents().find('body'); var text = $('p').text(); frame.html(text); } </script> </head> <body> <p>Vestibulum auctor, sapien aliquam laoreet tincidunt, tellus neque mattis ante, vestibulum facilisis felis magna vel nisl. Quisque hendrerit rutrum metus in tempus. Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p> <button type="button" onclick="addToframe()">Insert content</button> <iframe style="border: 1px solid #000; width: 550px;" id="frame"></iframe> </body> </html>
Result |
---|
Vestibulum auctor, sapien aliquam laoreet tincidunt, tellus neque mattis ante, vestibulum facilisis felis magna vel nisl. Quisque hendrerit rutrum metus in tempus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. |