Fred the Man Fred the Man - 27 days ago 22
Javascript Question

Create an iframe with only javascript

I have been struggling on one of those programing challenge sites for a while. It has a console type thing that lets me enter javascript and press a run button. I need to create an iframe inside of that webpage with another webpage inside of it (for example, im on thiswebsite.com/level1 and I need to create the iframe with thiswebsite.com/level2 inside of it).

Have tried creating iframes as follows:

document.getElementById('someDiv').innerHTML = '<iframe src="thissite.com/level2/" height= 300 width=400>';


However it does not run when I try this, is there an alternative way?
Thanks.

Answer

Use createElement method of document

var a = document.createElement('iframe');
a.src = "your path will go here"; //add your iframe path here
a.width = "1000";
a.height = "500";
document.querySelector('body').appendChild(a)

I just append the iframe to body. To append it to someDiv replace last line with below code

document.getElementById('someDiv').appendChild(a);