Html code as IFRAME source rather than a URL
According to W3Schools, HTML 5 lets you do this using a new "srcdoc" attribute, but the browser support seems very limited.
You can do this with a data URL. This includes the entire document in a single string of HTML. For example, the following HTML:
<html><body>foo</body></html>
can be encoded as this:
data:text/html;charset=utf-8,%3Chtml%3E%3Cbody%3Efoo%3C/body%3E%3C/html%3E
and then set as the src
attribute of the iframe. Example.
Edit: The other alternative is to do this with Javascript. This is almost certainly the technique I'd choose. You can't guarantee how long a data URL the browser will accept. The Javascript technique would look something like this:
var iframe = document.getElementById('foo'),
iframedoc = iframe.contentDocument || iframe.contentWindow.document;
iframedoc.body.innerHTML = 'Hello world';
Example
Edit 2 (December 2017): use the Html5's srcdoc attribute, just like in Saurabh Chandra Patel's answer, who now should be the accepted answer! If you can detect IE/Edge efficiently, a tip is to use srcdoc-polyfill library only for them and the "pure" srcdoc attribute in all non-IE/Edge browsers (check caniuse.com to be sure).
<iframe srcdoc="<html><body>Hello, <b>world</b>.</body></html>"></iframe>
use html5
's new attribute srcdoc
(srcdoc-polyfill) Docs
<iframe srcdoc="<html><body>Hello, <b>world</b>.</body></html>"></iframe>
Browser support - Tested in the following browsers:
Microsoft Internet Explorer
6, 7, 8, 9, 10, 11
Microsoft Edge
13, 14
Safari
4, 5.0, 5.1 ,6, 6.2, 7.1, 8, 9.1, 10
Google Chrome
14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24.0.1312.5 (beta), 25.0.1364.5 (dev), 55
Opera
11.1, 11.5, 11.6, 12.10, 12.11 (beta) , 42
Mozilla FireFox
3.0, 3.6, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 (beta), 50