Reputation: 1
On my index page amongst several different divs is a single iframe with id = 'myframe', that iframe has a src = order.html and that page has a bunch of different radio buttons and checkboxes with values associated with them.
I've currently run into a wall writing the javascript function to edit a div (with id = 'purchase') on the index page of this website to display current orders/purchases.
function addAlbum(boxElement){
var iframe = document.getElementById('myframe');
var s = iframe.contentWindow.document.getElementById('purchase').innerHTML;
i = boxElement.value.indexOf("|");
clean_string = boxElement.value.substring(0,i);
//price = parseInt(boxElement.value.substring(i +1, boxElement.value.length));
replaceString = "";
if(boxElement.checked){
s += '<div class="one_record">';
s += clean_string;
s += '</div>';
}
else{
replaceString = '<div class="one_record">';
replaceString += clean_string;
replaceString += '</div>';
s.replace(replaceString, "");
}
}
When I run my function I get an error saying: "Cannot read property 'contentWindow' of null" meaning that it cant find my iframe (id = 'myframe'). Any advice is most appreciated.
Upvotes: 0
Views: 964
Reputation: 5797
In the past I've found that you can not edit the contents of an iframe when you capture it through the ID with document.getElementById()
you need to go through the window.frames
i.e. window.frames.iFrameName.document.body.innerHTML
.
You should be able to access the IFrame's document like this (with you more or less are):
var frame = document.getElementById('frame');
frame.onload = function() {
var frameDoc = frame.contentDocument ? frame.contentDocument : frame.contentWindow.document;
frameDoc.body.innerHTML += '<br />Appended from the parent Page';
}
After correcting my own ignorance on the issue I took a closer look at what's going own with your code nothing really stood out. In fact at first I had problems replicating the issue cause your code actually worked for me. Usually this means that the iFrame has not loaded.
So I tried that and the only errors I was getting were that the innerHTML of the iFrame's element getElementById('purchase')
was NULL, not the contentWindow
.
And then it hit me, you are calling the function addAlbum(boxElement)
before the iframe exists in the DOM. With this HTML I got the exact same error in IE:
<html>
<head></head>
<body>
<script type="text/javascript">
var frame = document.getElementById('frame');
(function() {
var s = frame.contentWindow.document.getElementById('s1').innerHTML;
s += '<br />Appended from the parent Page';
})();
</script>
<iframe id="frame" src="internal.htm"></iframe>
</body>
</html>
Note how both the script and the iframe are in the body and the iframe is bellow the script. I am willing to bet you have an analog situation, because nothing else caused such a distinct error. Unfortunately I can't pinpoint your error without seeing your HTML.
Upvotes: 0