1

I am having file - index.html, that has embed script.js.

Script.js - is rendering html <a href="url.html" id="url"> tag.

I want to insert in index.html this code, that shows HREF value, that is rendered by script.js:

var d = document.getElementById( 'url' );
alert(d.href);

But this script is working only on tags, that are written index.html.

How to get the script work?

index.html

<script type="text/javascript" src="script.js"></script>
<script type="text/javascript">
var d = document.getElementById( 'url' );
alert(d.href);
</script>

script.js:

document.write("<iframe src=iframe.html></iframe>");

iframe.html:

<a href=url.html id=url>Test URL</a>

--- EDITED ---

My friend came up with this code:

<script type="text/javascript">
$(document).ready(function() {
var href = $("iframe").contents().find("a").attr('href');
alert(href);
});
</script>

But alert() is showing - "undefined"

Attorney
  • 11
  • 3
  • Can you Explain further this part: "I want to insert in index.html this code, that shows HREF value, that is rendered by script.js:" `var d = document.getElementById( 'url' ); alert(d.href);` " But this script is working only on tags, that are written index.html." – ErickBest Sep 24 '13 at 15:38

1 Answers1

2

You have a frame, document.getElementById() won't automatically access it. Try this:

var frame = document.getElementsByTagName("iframe")[0];

frame.contentWindow.document.getElementById("url");

In the first line, I get a reference to the frame by accessing the first <iframe> element of the page. There are several other methods of doing so.

ComFreek
  • 29,044
  • 18
  • 104
  • 156
  • I don`t know why, but this is not working for me. I made index.html like this: `var frame = document.getElementsByTagName("iframe")[0]; var a = frame.contentWindow.document.getElementById("url"); alert(a.href);` – Attorney Sep 24 '13 at 15:50
  • @Attorney What does 'not working' mean? Are there any errors in the JS dev console? – ComFreek Sep 24 '13 at 15:54
  • @Attorney Can you please post the full error message in your question? – ComFreek Sep 24 '13 at 16:22
  • frame.contentWindow is null or not an oject – Attorney Sep 24 '13 at 16:29
  • @Attorney Do you host the frame source on the same domain? – ComFreek Sep 24 '13 at 17:52
  • with sample test yes, but with the real one - no. But the sample isn`t working for either. – Attorney Sep 24 '13 at 19:17
  • @Attorney Do you run the sample from your hard drive (i.e. using the `file:///` protocol)? This could be an issue. Cross-domain iFrame access can't be done - not even using CORS, see [this question](http://stackoverflow.com/questions/6460200/can-cross-origin-resource-sharing-headers-authorize-x-domain-iframe-access). – ComFreek Sep 24 '13 at 20:11