views:

700

answers:

1

I've got this structure:

<div id="source1">
    <iframe src="foo.html"></iframe>
</div>
<div id="source2">
    <iframe src="foo.html"></iframe>
</div>

If I've got some js code inside foo.html, is there a way to tell which div it's in (without adding a parameter to the iframe code)?

+1  A: 

from foo.html, you can get the parent window with parent; once you're there, you can compare each iframe's contentWindow property with this - the one that matches is you.

Searching the parent for all iframes is the hardest part of this; it'd be easy to write quickly using a library like jQuery, but here's something hacked together quickly:

var mycontainer;
var iframes = document.getElementsByTagName("iframe");
for (var iter = 0; iter <iframes.length; iter++){
    if( iframes[iter].contentWindow && iframes[iter].contentWindow === window){
        mycontainer = iframes[iter].parentNode;
    }
}
DDaviesBrackett