Reputation: 1319
I have an Iframe inside of a page that has the src set to a file on the same local machine (not cross domain).
So I have a page that looks like this:
<html>
<head/>
<body><iframe id="something" src="somepage.html"/></body>
</html>
Inside of the iframe there is some contents
<html>
<head/>
<body>
<li>
<ul>stuff</ul>
</li>
</body>
</html>
My question is, I have a variable (in my index page) that is currently pointing to the element var element = <ul>stuff</ul>
which is inside of the iframe.
From this variable I want to be able to access the parent iframe and get the id 'something'.
I have been attempting some jquery using find with no luck
$(element).find('iframe')
And I am wondering where I am going wrong... I have googled other solutions but they are all related to being outside of the iframe looking in, I guess I am inside looking out! is there anyone else out there that could help shed some light?
Upvotes: 1
Views: 2325
Reputation: 382092
It seems to be very difficult to find the id of the iframe element without something like its name.
But supposing you know the name of the html file in the iframe ("somepage.html"), which seems natural, you can do this to get the element containing the iframe in the parent document :
var $matching = $(parent.document).find('iframe').filter(function(){
var srcTokens = this.src.split('/');
return srcTokens[srcTokens.length-1]=='somepage.html';
});
Here's the "somepage.html" file I used to test, logging the id in the console :
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
</head>
<body>
<li>
<ul>stuff</ul>
</li>
<script>
var $matching = $(parent.document).find('iframe').filter(function(){
var srcTokens = this.src.split('/');
return srcTokens[srcTokens.length-1]=='somepage.html';
});
console.log($matching.attr('id'));
</script>
</body>
</html>
EDIT : as was seen by Serjio, it's possible to use location.href
if you don't know the name of the html file.
Upvotes: 1
Reputation: 5390
At first, it's a good practice to set name for iframe if you want to access some data in it. After that to access iframe's DOM you can use:
$('ul', window.frames['iframe_name'].document);
To access global variables
alert(window.frames['iframe_name'].some_global_var_or_function_of_iframe)
If you want to get some parent data inside iframe:
$('selector', parent.document) // for DOM
alert(parent.some_global_var_or_function_of_parent_window)
EDIT So in your case just use:
$('iframe', parent.document).filter(function(iframe){
// you can compare iframes like this
return iframe.getAttribute('src') == location.href
}).attr('id')
Upvotes: 1