How to pick element inside iframe using document.getElementById

nik
nik
Member
166 Points
6 Posts

I have with iframe as:

<iframe id="myIframe"></iframe>

In the iframe I have hidden field as

<input id="hdnSelected" name="hdnSelected" type="hidden" value="myhiddenvalue" />

I want the value of this hidden input field on parent page.

Views: 13266
Total Answered: 2
Total Marked As Answer: 0
Posted On: 08-Jan-2018 03:16

Share:   fb twitter linkedin
Answers
hambi
hambi
Member
56 Points
2 Posts
         

Use following javascript code:

var hdnSelectedInput = document.getElementById('myIframe')
                       .contentWindow.document.getElementById('hdnSelected');

contentWindow is supported by all browsers including the older versions of IE.

Note: If the iframe's src is from another domain, you won't be able to access its content due to the Same Origin Policy. 

Posted On: 08-Jan-2018 05:27
The last sentence is very important ;) your frame's source must be on the same domain of your page
 - Rahul Kiwitech  08-Jan-2018 05:33
beginer
beginer
Member
1328 Points
43 Posts
         
var x = document.getElementById("myIframe");
var y = (x.contentWindow || x.contentDocument);
if (y.document)
    y = y.document;
var hdnSelectedInput = y.getElementById('hdnSelected');

The contentDocument property returns the Document object generated by a frame or iframe element.

Posted On: 09-Jan-2018 23:07
 Log In to Chat