jQuery – create iframe with content

Sometimes we need to create inline iframe with content generate from jQuery/Javascript. This iframe will not have src attribute. One use case is to run some html/javascript/css code with its own context. Here is code snippet for it.

Create iframe and add content to its document object

This example add a simple html to create iframe document object. Note that you can also add css and javascript in content.

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>

<div id="id1"></div>

<script type="text/javascript">
$(function() {
  var iframeDoc = $("#id1 iframe")[0].contentDocument;
  iframeDoc.write("<p>Test content in iframe created from Javascript.</p>");
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit


Click here to write/view comments