1

I am trying to retreive data using document.getElementsByName but the function returns empty if my element is inside a nested HTML document. I am not sure if this is the reason but the fact is that right before the nested HTML the function works fine.

here is a simplification:

<html>
  ...
   <iframe name="contentFrame"> // getElementsByName can find this element
      <html>
         ...
           <input name="ship_no">   // getElementsByName  returns empty
         ...
      </html>
  ...
 </html>

I did some searching and couldn't find anything related. Can anyone think of a workaround for this problem?

David912
  • 378
  • 1
  • 2
  • 11
  • 2
    it is because document loaded into an iframe is considered a separate one – Trash Can Jul 13 '18 at 20:52
  • _"Can anyone think of a workaround for this problem?"_ - how about, some basic research? https://www.google.com/search?q=getElementsByName%20access%20element%20inside%20iframe -> https://stackoverflow.com/questions/14451358/how-to-pick-element-inside-iframe-using-document-getelementbyid – CBroe Jul 13 '18 at 20:54

1 Answers1

2

An iframe is considered a different document from the current document.

First get the iframe and then get the iframe's contentDocument.

var iframe = document.getElementById('iframeId');
var innerDoc = iframe.contentDocument || iframe.contentWindow.document;

You can then call innerDoc.getElementsByName.

Unmitigated
  • 76,500
  • 11
  • 62
  • 80