Reputation: 13534
I have following iframe in a parent page:
<html>
....
<iframe src="child.html" name="variedName" id="variedId"></iframe>
...
</html>
Is there any way that make Javascript from child.html
to get the name
value or the id
of the iframe that included it?
I need this because I want to add some markup around the iframe that is going to include child.html
in the parent page using window.parent
Upvotes: 2
Views: 2528
Reputation: 4241
Besides the presented solutions, You can use this:
parent.document.getElementsByName(window.name)[0];
Documentation: https://developer.mozilla.org/en-US/docs/Web/API/document.getElementsByName
Or this:
parent.document.querySelector('iframe[src="'+location+'"]');
Documentation: https://developer.mozilla.org/en-US/docs/Web/API/document.querySelector
Or this "frankencode":
(function(){
for(var i=0,frames=parent.frames,l=frames.length;i<l;i++)
{
if(frames[i].window===window)
{
return frames[i].window;
}
}
})();
If you have jQuery:
$('iframe[name="'+window.name+'"]',parent); //method 1
$('iframe[src="'+location+'"]',parent); //method 2
$('iframe',parent).filter(function(){ //a different method
return this.window===window;
}).eq(0);
And many more ways...
Upvotes: 0
Reputation: 57709
Yes, but only if the pages share the same origin.
You can do something like:
var parent_window = window.parent;
iframes = parent_window.document.getElementsByTag("iframe");
if (iframes[0].window === window) {
// found it
}
The if
statement might need some tweaking but I think this works.
Upvotes: 2
Reputation: 2085
Well, the quick and dirty solution would be to give the iframe the same name and id and access the iframe within the child page like this:
parent.document.getElementById(window.name);
Upvotes: 3