Dynamically Generating an Iframe
On this page, JavaScript is used to create an iframe element and insert it into the document. The createElement
method is used to dynamically generate the iframe. Either the appendChild
or insertBefore
method can be used to place the iframe in the document. The setAttribute
method can be used to add id
, src
, and other attributes.
The following iframe was created and placed in the document using these methods. The JavaScript for the example is displayed below.
JavaScript to Create and Insert Iframe
The JavaScript displayed here was used to create the iframe above:
var ifrm = document.createElement('iframe');
ifrm.setAttribute('id', 'ifrm'); // assign an id
//document.body.appendChild(ifrm); // to place at end of document
// to place before another page element
var el = document.getElementById('marker');
el.parentNode.insertBefore(ifrm, el);
// assign url
ifrm.setAttribute('src', 'demo.html');
The insertBefore
method was used for this example while the appendChild
alternative is shown in code comments.