Find an IFrames id

There is an HTML5 (originally IE extension) property frameElement on window:

alert(frameElement.id);

But this is not globally supported; you won’t get it in Google Chrome (at the time of writing; version 7) or in older versions of the other popular non-IE browsers.

Without this extension, you have to do it manually. Go to the parent window, and search through all its iframes to see if the document contained within is your own document:

function getFrameElement() {
    var iframes= parent.document.getElementsByTagName('iframe');
    for (var i= iframes.length; i-->0;) {
        var iframe= iframes[i];
        try {
            var idoc= 'contentDocument' in iframe? iframe.contentDocument : iframe.contentWindow.document;
        } catch (e) {
            continue;
        }
        if (idoc===document)
            return iframe;
    }
    return null;
}

alert(getFrameElement().id);

(The contentDocument workaround is necessary because IE<8 doesn’t support it; the try...catchis needed to avoid security exceptions stopping the loop when it meets a frame from a different domain.)

Leave a Reply

Your email address will not be published. Required fields are marked *