Javascript

How do I create an iframe element and set the HTML of it dynamically

27 September 2026 · 6 min read

How do I create an iframe element and set the HTML of it dynamically

In today’s dynamic web landscape, the ability to control and customize web content on the fly is paramount for creating interactive and secure user experiences. Often, developers encounter scenarios where they need to isolate content, embed external applications, or even generate rich text editors directly within their web pages. This is where understanding how to create an iframe element and set the HTML of it dynamically becomes an invaluable skill. An iframe, or inline frame, allows for the embedding of another HTML document within the current document. While traditionally used for static content, modern web development frequently demands the ability to programmatically inject and manage the content of these frames, opening up a world of possibilities for complex web applications and controlled content rendering. This guide will walk you through the essential techniques, best practices, and security considerations involved in this powerful process.

Understanding Iframes and Their Core Functionality

An iframe is essentially a nested browsing context, effectively a mini web page embedded within another. It’s defined by the <iframe> HTML tag and is widely used for various purposes, such as embedding third-party content like YouTube videos, Google Maps, or payment gateways. What makes them particularly interesting for dynamic content is their ability to load independent documents, complete with their own CSS, JavaScript, and HTML structure, all without interfering with the parent page’s environment. This isolation is a double-edged sword: great for preventing style conflicts, but challenging when attempting to manipulate their internal content directly.

However, this isolation is precisely what makes iframes powerful for security. The Same-Origin Policy is a critical security mechanism that prevents a document or script loaded from one origin from interacting with a resource from another origin. For iframes, this means that a parent page cannot directly access or modify the content of an iframe if the iframe’s source (src) is from a different domain. When we talk about dynamically setting HTML, we are generally referring to iframes that are either created with no src attribute or iframes whose content is being written from the same origin. Understanding this policy is fundamental before diving into dynamic manipulation, especially when dealing with the sandbox attribute, which further restricts iframe capabilities.

Beyond security, iframes are excellent for creating encapsulated components. Imagine a scenario where you want to allow users to preview generated HTML code without risking interference with your main page’s scripts or styles. An iframe provides that clean, contained environment. This isolation extends to performance as well; if an iframe’s content crashes, it’s less likely to bring down the entire parent page, though excessive use can still impact overall page load times and memory consumption.

Creating an Iframe Dynamically with JavaScript

To create an iframe element dynamically, JavaScript’s Document Object Model (DOM) manipulation capabilities are your primary tool. This process typically involves using document.createElement() to instantiate the iframe, followed by setting various attributes and finally appending it to the desired location within your document. This method provides full control over the iframe’s initial state before any content is loaded into it.

Here’s a basic example of how to programmatically create an iframe and add it to your page:

// Create a new iframe element const dynamicIframe = document.createElement('iframe'); // Set desired attributes dynamicIframe.id = 'myDynamicIframe'; dynamicIframe.style.width = '100%'; dynamicIframe.style.height = '300px'; dynamicIframe.style.border = '1px solid ccc'; // Add a sandbox attribute for security, restricting capabilities // For dynamic content, 'allow-scripts' and 'allow-same-origin' are often needed. dynamicIframe.sandbox = 'allow-scripts allow-same-origin'; // Append the iframe to an existing element in the DOM (e.g., a div with id="iframe-container") const container = document.getElementById('iframe-container'); if (container) { container.appendChild(dynamicIframe); console.log('Iframe created and appended.'); } else { console.error('Iframe container not found.'); } 

This JavaScript DOM manipulation ensures that the iframe is generated client-side, making it highly flexible. You can place it anywhere in your document structure, apply specific styling, and even assign a unique ID for later reference. The sandbox attribute is crucial for security, especially when you plan to inject user-generated or external content. Without it, or with overly permissive settings, an iframe could potentially execute malicious scripts that affect the parent page. It’s a powerful security feature that should be carefully configured based on your specific use case, balancing functionality with the need for isolation.

Dynamically Setting Iframe Content

Once an iframe element has been created and appended to the DOM, the next step is to populate it with HTML content dynamically. This is where the contentWindow and contentDocument properties of the iframe become essential. The contentWindow property references the Window object of the embedded document, while contentDocument references the Document object itself.

To inject HTML into an iframe, you generally follow a sequence of opening the document, writing the content, and then closing the document. This process effectively overwrites the iframe’s current content with the new HTML.

  1. Access the iframe’s document: Get a reference to the iframe’s contentDocument.
  2. Open the document: Call iframe.contentDocument.open(). This clears the iframe’s current content and prepares it for new input.
  3. Write the HTML: Use iframe.contentDocument.write('Your HTML string here') to insert the desired HTML markup. This can be a complete HTML document structure, including ``, <head>, and <body>, or just a snippet.
  4. Close the document: Call iframe.contentDocument.close(). This signals that writing is complete and causes the browser to parse and render the newly written content.

The most straightforward approach for dynamically setting iframe content involves accessing its contentDocument and using its open(), write(), and close() methods. This allows for direct injection of HTML strings. For example:

// Assuming 'dynamicIframe' is the iframe element created earlier if (dynamicIframe.contentDocument) { dynamicIframe.contentDocument.open(); dynamicIframe.contentDocument.write('<html><head><title>Dynamic Content</title><style>body { font-family: sans-serif; margin: 20px; }</style></head><body><h1>Hello from Dynamic Iframe!</h1><p>This content was injected via JavaScript.</p><a href="https://example.com" target="_blank">Visit Example</a></body></html>'); dynamicIframe.contentDocument.close(); console.log('Iframe content set dynamically.'); } 

This process is typically used when the iframe’s content is generated entirely by the parent page’s JavaScript and doesn’t rely on a separate URL. It’s a powerful technique for scenarios like rich text editors, code playgrounds, or displaying user-generated content in a controlled, isolated environment. Remember that the document.write() method can be problematic if the iframe has already fully loaded external content, potentially leading to unexpected behavior or an empty page. For same-origin content, an alternative is to access the iframe’ Question & Answer :

I’m trying to create an iframe from JavaScript and fill it with arbitrary HTML, like so:

var html = '<body>Foo</body>'; var iframe = document.createElement('iframe'); iframe.src = 'data:text/html;charset=utf-8,' + encodeURI(html); 

I would expect iframe to then contain a valid window and document. However, this isn’t the case:

> console.log(iframe.contentWindow);
null

Try it for yourself: http://jsfiddle.net/TrevorBurnham/9k9Pe/

What am I overlooking?

Allthough your src = encodeURI should work, I would have gone a different way:

var iframe = document.createElement('iframe'); var html = '<body>Foo</body>'; document.body.appendChild(iframe); iframe.contentWindow.document.open(); iframe.contentWindow.document.write(html); iframe.contentWindow.document.close(); 

As this has no x-domain restraints and is completely done via the iframe handle, you may access and manipulate the contents of the frame later on. All you need to make sure of is, that the contents have been rendered, which will (depending on browser type) start during/after the .write command is issued - but not nescessarily done when close() is called.

A 100% compatible way of doing a callback could be this approach:

<html><body onload="parent.myCallbackFunc(this.window)"></body></html> 

Iframes has the onload event, however. Here is an approach to access the inner html as DOM (js):

iframe.onload = function() { var div=iframe.contentWindow.document.getElementById('mydiv'); };