
#Javascript iframe how to
This technique will be helpful for you if you want to open some user specified code in an iframe dynamically and show output. Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, Python, PHP, Bootstrap, Java, XML and more. 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. Then we have used the appendChild() function to append it to some DOM element on our HTML page, in this case a tag with id attribute as myDIV. In the JavaScript code above, we have first used the document.createElement() function to create an iframe element. In the code above, the variable htmlcode will hold the HTML code that you want to run inside the iframe.

div tag in which iframe will be added should have id attribute with value myDIVĭocument.getElementById("myDIV").appendChild(iframe) var iframe = document.createElement('iframe')

But one thing is for sure, that we will have to use document.createElement('iframe') to create an iframe dynamically using JavaScript, and we will have to append it to the DOM of our HTML page, for which we can either simply add the iframe to the tag like in the above example, or we can add the iframe inside a particular div tag.īelow is the code, using which we can create an iframe dynamically and then add out HTML code to it.
Iframe.src = 'data:text/html charset=utf-8,' + encodeURI(html) īut this code will not work for complex HTML code. An