js create iframe element code example

Example 1: use javascript to control iframe elements

<iframe id="myIFrame" src="thispage.html"
    width="100%" height="600"
    frameBorder="2">
</iframe>

// Get the iframe
const iFrame = document.getElementById('myIFrame');

// Let's say that you want to access a button with the ID `'myButton'`,
// you can access via the following code:
const buttonInIFrame = iFrame.contentWindow.document.getElementById('myButton');

// If you need to call a function in the iframe, you can call it as follows:
iFrame.contentWindow.yourFunction();

Example 2: document.createElement('iframe');

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');