3

So I'm not that great with Javascript so I'll put that forward right away. That being said, I've looked up as much as I could on this particular problem before asking, but the suggestions haven't solved my issues. I'm ultimately trying to pull all of the links from an iframe window on the same domain as the main page. Then I want to basically search that link array to match it with the current page to trigger a CSS modification to the html code (this part is not coded yet, FYI). So here is the part I have so far: Side note: The confirms are in there to debug the code and try to tell me where it's failing and what my queries are returning, they won't stay obviously when this is finished. I appreciate any advice that may help me fix this!

<script type="text/javascript">
// main is the iframe that I'm trying to search for a tags
document.getElementById("main").onload = function() {
 confirm("test");
 var main = document.getElementById("main");
 var anchors = main.contentWindow.document.getElementsByTagName('a');
 confirm(anchors[1]);
 for (var i in anchors) {
  confirm(anchors[i].getAttribute("href"));
 }
};
</script>
Jimi
  • 901
  • 7
  • 11
Matthew Walker
  • 193
  • 1
  • 15

2 Answers2

1

I have created a plunker for you its working. I think its the placement of code in your file is causing the problem.

<iframe id="main" src="content_if.html"></iframe> 
 <script>
   // main is the iframe that I'm trying to search for a tags
  document.getElementById("main").onload = function() {
    confirm("test");
    var main = document.getElementById("main");
    var anchors = main.contentWindow.document.getElementsByTagName('a');
    confirm(anchors[1]);
    for (var i in anchors) {
        confirm(anchors[i].getAttribute("href"));
    }
  };

 </script>

You should use jQuery to do this in a cross browser way. Include jQuery in page

<script src="https://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>

and follow this post

Community
  • 1
  • 1
Saqueib
  • 3,484
  • 3
  • 33
  • 56
0

There is a similar post about doing this and I agree with Mohamed-Yousef. If you can use jquery then you should do so!

$("#main").contents().find("a").each(function(element) {
    // "each" will iterate through every a tag and inject them as the "element" argument
    // visible in the scope of this anonymous function
});

EDIT: You must include

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

above your code that references the $ variable. There are other ways to use jQuery but this is probably the easiest.

Community
  • 1
  • 1
Jimi
  • 901
  • 7
  • 11
  • So when I try this instead it just returns ReferenceError: Cannot find variable $, I definitely see why this would be the better option but for some reason by data is still not being parsed properly? – Matthew Walker Dec 05 '14 at 05:25
  • Hey, see my most recent edit regarding this. Cheers! – Jimi Dec 05 '14 at 05:33