Categories
JavaScript Answers

How to create an iframe with given HTML dynamically with JavaScript?

Spread the love

Sometimes, we want to create an iframe with given HTML dynamically with JavaScript.

In this article, we’ll look at how to create an iframe with given HTML dynamically with JavaScript.

How to create an iframe with given HTML dynamically with JavaScript?

To create an iframe with given HTML dynamically with JavaScript, we can use the createElement method.

For instance, we write

const iframe = document.createElement("iframe");
const html = "<body>hello world</body>";
document.body.appendChild(iframe);
iframe.contentWindow.document.open();
iframe.contentWindow.document.write(html);
iframe.contentWindow.document.close();

to call createElement to create an iframe.

Then we call appendChild to append the iframe as child of the body element.

Next, we call iframe.contentWindow.document.open to open the iframe for writing.

Then we call iframe.contentWindow.document.write with html to write the html content to the iframe.

Finally, we call close to stop writing.

Conclusion

To create an iframe with given HTML dynamically with JavaScript, we can use the createElement method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *