views:

456

answers:

3

I though this would be simple enough but I can't find the answer. I need to know how I can access an iframes name from withing said iframe. I was trying something like this but it's not working.

<iframe name="thename">
<script type="text/javascript">
alert(parent.name);
</script>
</iframe>
A: 

Something like this should work:

parent.document.getElementById('idhere').name;

You have to use the parent and then get the element either byId, Name, etc... then access the name property.

So your code should be like:

<iframe name="thename">
 <script type="text/javascript">
   var iframeName = parent.document.getElementById('idhere').name;
 </script>
</iframe>
Todd Moses
A: 

Well, an IFRAME element shouldn't contain anything, it's targeting another document. So using a SCRIPT tag inside an IFRAME doesn't make alot of sense. Instead, use the SCRIPT inside the called document, e.g.

iframe_caller.html:

<html>
 <body>
  <iframe id="theIframe" name="theIframe" src="iframe_doc.html"></iframe>
 </body>
</html>

iframe_doc.html:

<html>
 <body>
  <script type="text/javascript">
    var iframes= parent.document.getElementsByTagName("iframe");
    document.write(iframes[0].getAttribute("id"));
  </script>
 </body>
</html>

Note I'm using parent.document.function() there.

bdl
+5  A: 

You were nearly right. Setting the name attribute on a frame or iframe sets the name property of the frame's global window object to that string. (Not parent, which refers to the window of the document that owns the frame.)

So unless some other script has deliberately changed the name, it's as simple as:

1.html:
<iframe name="tim" href="2.html"></iframe>

2.html:
<script type="text/javascript">
    alert(window.name); // tim
</script>
bobince