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?

asked Jul 13, 2018 at 20:50
2
  • 2
    it is because document loaded into an iframe is considered a separate one Commented Jul 13, 2018 at 20:52
  • "Can anyone think of a workaround for this problem?" - how about, some basic research? google.com/… -> stackoverflow.com/questions/14451358/… Commented Jul 13, 2018 at 20:54

1 Answer 1

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.

answered Jul 13, 2018 at 20:54
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.