To create iframe inside a div dynamically

Hi,

I want to create an iframe inside div.I am having tables inside the div.I want to create iframes before the table.

Any help would be greatly appreciated.

I threw this together and it worked in Firefox. The page being loaded by the new iframe is called “newtest.html”

<html>
<head>
<title>Can an iframe be built using the dom?</title>
<script type=“text/javascript”>
function addIframe() {
var target = document.getElementById(“targetDiv”);
var newFrame = document.createElement(“iframe”);
newFrame.setAttribute(“src”, “newtest.html”);
target.appendChild(newFrame);
}
</script>
</head>

<body>
Blah Blah Blah
<div id=“targetDiv”></div>
Blah Blah Blah
<script type=“text/javascript”>
addIframe();
</script>
</body>
</html>

FYI: Sitepoint has a great book called “The Javascript Anthology”. Chapter 5 of the book covers this sort of thing and you can download that chapter free.

floater

1 Like

The requirement was to insert the iframe presumably as the first element in the div, so

target.appendChild(newFrame);

probably would need to be

target.insertBefore( newFrame, target.firstChild );

Logic Ali is correct. The code I provided would insert the iframe after any content already in the div.

my bad!

floater

Hi,

Thank u all.It works fine.