0

I have this piece of code. I can see the iframe content but it seems that edp0 is always undefined. Why?

<!DOCTYPE html><html>
<body>
   <iframe src="DOM-copyB.html"></iframe>
   <script>
      ed = document.getElementsByTagName('iframe')[0].contentDocument;
      edp0 = ed.getElementsByTagName('p')[0];
      edp1 = ed.getElementsByTagName('p')[1];
      alert(edp0);
   </script>
</body></html>

Here is DOM-copyB.html:

<!DOCTYPE html><html><head></head>
<body>
   <p>A<b>B</b>C</p>
   <p>1<b>2</b>3</p>
</body></html>
Chong Lip Phang
  • 8,755
  • 5
  • 65
  • 100

2 Answers2

0

I'm not sure about javascript. But jusing jQuery would be much easier:

<iframe src="DOM-copyB.html" id="myFrame"></iframe>

<script>
$("#myFrame").contents().find("p");
</script>
Yorick de Wid
  • 859
  • 11
  • 19
0

Your JavaScript is probably running before the iframe's content is loaded. Try running your code in window.onload and see if that helps:

window.onload = function() {
    ed = document.getElementsByTagName('iframe')[0].contentDocument;
    edp0 = ed.getElementsByTagName('p')[0];
    edp1 = ed.getElementsByTagName('p')[1];
    alert(edp0);
};

If you're not running the code from a server, though, I suspect after you get the code to successfully reference the iframe content, you'll get an error like this in the Chrome console due to Cross-Origin security:

Uncaught SecurityError: Failed to read the 'contentDocument' property from 'HTMLIFrameElement': Blocked a frame with origin "null" from accessing a frame with origin "null". Protocols, domains, and ports must match.

If you run them from a server, that error should go away. See this question for more details on that: Using iframe with local files in Chrome

Community
  • 1
  • 1
MikeJ
  • 2,179
  • 13
  • 16