GetElementsByTagName ('a'); does not work?

So, I am doing this:

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

It works great. Then I want to do this:

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

but that will not work. It ends with undefined. I can do:

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

and this is normal. Should I not get all the "a" in the "iframe"?

Edit: Thus, I am not the owner of the iframe, and now I get the impression that I cannot access anything that generates an iframe, which means that I think I'm screwed.

+6
source share
5 answers

Use ..

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

Specification .

Then you can call getElementsByTagName('a') on iframeDoc . Alternatively, you can access iframeDoc.links , which is not exactly the same, but may be what you want.

Of course, all this depends on access to the iframe document , which does not violate a policy of the same origin .

+10
source

getElementsByTagName() returns the NodeList that you will 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 the children inside the document to be in the frame, you 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 in older versions of IE.

+4
source
 stuff[0].contentWindow.document.getElementsByTagName('a') 

should create an object similar to an array containing all references in a null iframe.

You need to use contentWindow.document because the <iframe> does not contain nodes in the current document - this is a frame, the contentWindow property points to another window with its own document.

+3
source

getElementsByTagName returns an array of matching elements. To access an individual IFRAME, you must use stuff[0] , for example.

+2
source

Why does everyone suggest contentWindow.document when you can just use contentDocument instead?

Of course, both work, but I prefer to use what I mean. If I want a window, I use contentWindow . If I need a document, I use contentDocument .

0
source

Source: https://habr.com/ru/post/908867/


All Articles