Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML5

HTML iframe Without src Attribute

5.00/5 (1 vote)
2 Nov 2015CPOL 36.7K  
The HTML tag is intended to embed an inline frame within an HTML document. This article explores the possibility to inject HTML content from the same source to the inline frame.

The HTML <iframe> tag denotes an inline frame within the HTML document. The primary usage of the inline frame is to embed another document within the current HTML document. In order to embed the intended document within the <iframe>, the address of the target document should be specified as src attribute value.

The following simple code snippet shows how to embed a page within another HTML document.

HTML
<!DOCTYPE html> 
<html> 
    <body> 
        <iframe src="http://www.duleekag.blogspot.com" 
	width="200" height="200"> 
            <p>iframes are not supported.</p> 
        </iframe> 
    </body>
</html>

The paragraph tag (<p>) is used to indicate the browsers that do not support this tag.

The intended purpose of <iframe> is to embed another document within the current HTML document. However, once, there was a need to inject a group of block elements coded elsewhere in the document into an <iframe>. Unorthodox it may sound, it was achieved in the following manner:

HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>iframe without src attribute</title>

<script type="text/javascript">
    function onTryItClick() {
        var content = document.getElementById("iframecontent").innerHTML;
        var iframe = document.getElementById("myiframeid");

        var frameDoc = iframe.document;
        if (iframe.contentWindow)
            frameDoc = iframe.contentWindow.document;

        frameDoc.open();
        frameDoc.writeln(content);
        frameDoc.close();
    }
</script>
</head>
<body>
    <div id="iframecontent" style="display: none;">
        <b>Hello World!</b> <br /> <i>Hello Again !</i>
    </div>

    <div style="margin: auto; width: 80%;">
        <iframe height="100" width="100%" 
        src="about:blank" name="myiframe"
         id="myiframeid"> </iframe>
        <br />
        <button id="tryIt" onclick="onTryItClick()">Try It</button>
    </div>
</body>
</html>

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)