Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getElementsByTagName('a'); not working?

So I do this:

var stuff = document.getElementsByTagName('iframe');

Works fine. Then I want to do this:

var other = stuff.getElementsByTagName('a');

but it doesn't work. It ends up being undefined. I can do:

var other = document.getElementsByTagName('a');

and it's fine. Should I not be able to get all the 'a' in 'iframe'?

Edit: So I don't own the iframe and am now under the impression that I can't access anything the iframe generates which meansI guess I'm screwed.

like image 380
townie Avatar asked Feb 20 '12 04:02

townie


2 Answers

Use..

var iframe = document.getElementsByTagName('iframe')[0],
    iframeDoc = iframe.contentWindow.document;

Specification.

Then, you can call getElementsByTagName('a') on iframeDoc. Alternatively, you could access iframeDoc.links, which isn't quite the same but may be what you want.

Of course, this all relies on the access to the iframe's document not violating Same Origin Policy.

like image 150
alex Avatar answered Oct 17 '22 09:10

alex


getElementsByTagName() returns a NodeList, which you'll need to iterate over. To iterate over it, you can do:

for (var i = 0; i < stuff.length; i++) {   
    var other = stuff[i].getElementsByTagName('a');
}  

However, getElementsByTagName('a') asks for children inside the current document, which is almost certainly not what you want. If you want children inside the document in the frame, you'll need to do:

for (var i = 0; i < stuff.length; i++) {   
    var other = stuff[i].contentWindow.document.getElementsByTagName('a');
}  

This will work if you have multiple iframes, and in older versions of IE.

like image 33
Timothy Jones Avatar answered Oct 17 '22 09:10

Timothy Jones