getElementsByTagName is null or undefined, only in IE - and only in one particular spot in the function

njj56 picture njj56 · Jun 22, 2012 · Viewed 8.8k times · Source

Possible Duplicate:
getElementById.contentDocument error in IE

listed below is my javascript code. What it does is searches the whole document for all iframes, then searches the iframes for all images. The parent and child frames are all my code on the same domain. The code works fine in chrome, FF and safari, but not IE. Here is the error I'm getting.

Microsoft JScript runtime error: Unable to get value of the property 'getElementsByTagName': object is null or undefined

And here is my code.

<script language="javascript">
var IMGmatches = [];
var IMGelems = document.getElementsByTagName("img");
var iframes = document.getElementsByTagName('iframe');
var l = IMGelems.length;
var m = iframes.length;
var i;
var j;
for (i = 0; i < l; i++) IMGmatches[i] = IMGelems[i];
for (j = 0; j < m; j++) {
    IMGelems = iframes[j].contentDocument.getElementsByTagName("img");
    l = IMGelems.length;
    for (i = 0; i < l; i++) {
        IMGmatches.push(IMGelems[i]);
        document.getElementById("HM").src = IMGelems[i].src;
        alert('IMGelems[i].src : ' + IMGelems[i].src);
    }
}

The error is happening at line:

IMGelems = iframes[j].contentDocument.getElementsByTagName("img");

Does anyone see or know why this could be happening only in IE? Thank you for your help.

Answer

Florian Margaine picture Florian Margaine · Jun 22, 2012

From MDN documentation:

The active document in the inline frame's nested browsing context. Not supported in Internet Explorer 7 and earlier; use contentWindow.document instead.