How to Convert an HTML String to an iFrame in JavaScript?

Estimated read time 2 min read

To convert an HTML string to an <iframe> in JavaScript, you can create a new <iframe> element, set its srcdoc attribute to the HTML string, and append the <iframe> element to the document. The srcdoc attribute is a new HTML5 attribute that allows you to specify the contents of an <iframe> as a string, rather than loading a separate document.

Here’s an example:

function htmlToIFrame(html) {
  var iframe = document.createElement("iframe");
  iframe.srcdoc = html;
  return iframe;
}

In this example, the htmlToIFrame function takes an HTML string as its argument and creates a new <iframe> element. The srcdoc attribute of the <iframe> element is set to the HTML string, and the <iframe> element is returned by the function.

To use this function, you can pass a string of HTML to the function:

var html = "<html><body><h1>Hello World!</h1></body></html>";
var iframe = htmlToIFrame(html);
document.body.appendChild(iframe);

In this example, a string of HTML is stored in the html variable. The htmlToIFrame function is then called with the html argument, and the resulting <iframe> element is appended to the document. The contents of the <iframe> will display the HTML string.

Note that the srcdoc attribute is supported in modern browsers, but may not be supported in older browsers. If you need to support older browsers, you can use an alternative solution such as dynamically writing the HTML string to a new document within the <iframe>.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply