3

I am creating a page which contains iframe. My aim is to create a javascript that will add to the head of the iframe content.

But I always get the error implying iframe.contentDocument is null.

Code for main page

<html>
<head>
<title>Sample "Hello, World" Application</title>
<script type="text/javascript" >
function sizeFrame() {
try{
    var ifrm = document.getElementById("CFrame");
    var bt = ifrm.contentDocument.createElement("base");
    bt.setAttribute("target", "_parent");
    ifrm.contentDocument.getElementsByTagName("head")[0].appendChild(bt);
}
catch (er)
{alert(er);}
}
</script>
</head>
<body>
<div id="sidecontainer">
<iframe id="SFrame" name="SearchFrame" frameborder ="0" width="500" height="100" scrolling="no" src="SearchBox.html"></iframe>
</div>
<div id="content">
<iframe id="CFrame" name="ContentFrame" frameborder="0" height="1000px" width="1000px" onload="sizeFrame()" scrolling="no" src="ContentFrame.html"></iframe>
</div>
</body>
</html>

Code for the Iframe ContentFrame.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
</head>
<body>
    <div id="input">
    test
    </div>
</body>
</html>
MikeNQ
  • 653
  • 2
  • 15
  • 29

2 Answers2

2

I suggest you try

ifrm.contentWindow.document.getElementById("id")
shuaqiu
  • 113
  • 3
  • Thanks, another error (TypeError: Cannot getElementById of undefined). And the requirement changed, so now I need to create a new "base" tag and add it to the iframe. – MikeNQ Dec 05 '12 at 01:39
0

Use the frame window name to create your element as you do in the main window like the following

ContentFrame.document...

In other word access the window name.

In addition your iframe window does not has any element with id value equals to "id".

SaidbakR
  • 13,303
  • 20
  • 101
  • 195