How to insert HTML content into an iFrame using jQuery

Topic: JavaScript / jQuery« Prev|Next »

Answer: Use the jQuery contents() method

You can use the jQuery contents() method in combination with the find(), val() and html() method to insert text or HTML inside an iframe body.

  • <!DOCTYPE html>
  • <html lang="en">
  • <head>
  • <meta charset="UTF-8">
  • <title>jQuery Insert HTML inside an iFrame</title>
  • <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
  • <style type="text/css">
  •     textarea, iframe{
  •         display: block;
  •         margin: 10px 0;
  •     }
  • </style>
  • <script type="text/javascript">
  •     function updateIframe(){
  •         var myFrame = $("#myframe").contents().find('body');
  •         var textareaValue = $("textarea").val();
  •         myFrame.html(textareaValue);
  •     }
  • </script>
  • </head>
  • <body>
  •     <textarea rows="5" cols="50" placeholder="Type HTML or text here..."></textarea>
  •     <button type="button" onclick="updateIframe()">Insert Content</button>
  •     <iframe id="myframe"></iframe>
  • </body>
  • </html>

Related FAQ

Here are some more FAQ related to this topic:

 
Close

Your Feedback:

 

We would love to hear from you! Please say something.