src attribute of the
iframe tag to create an iframe and add the HTML code to it.
But how can you do so dynamically, where you do not have any HTML file to show inside the iframe, rather you just have the HTML/CSS code.
Well, if this is the problem you are facing, you are at the right place.
var iframe = document.createElement('iframe'); var html = '<body>Foo</body>'; iframe.src = 'data:text/html;charset=utf-8,' + encodeURI(html); document.body.appendChild(iframe);
<body> tag like in the above example, or we can add the iframe inside a particular
Below is the code, using which we can create an iframe dynamically and then add out HTML code to it.
var iframe = document.createElement('iframe'); // div tag in which iframe will be added should have id attribute with value myDIV document.getElementById("myDIV").appendChild(iframe); // provide height and width to it iframe.setAttribute("style","height:100%;width:100%;"); iframe.contentWindow.document.open(); iframe.contentWindow.document.write(htmlcode); iframe.contentWindow.document.close();
In the code above, the variable
htmlcode will hold the HTML code that you want to run inside the iframe.
<div> tag with
id attribute as myDIV.
Then we opened the iframe, added the HTML code which we want to run inside the iframe using the
document.write() function, and then we closed the iframe element.
This technique will be helpful for you if you want to open some user specified code in an iframe dynamically and show output.
SHARE YOUR THOUGHTS WITH US!