0

I find that it's very hard to select elements in an iframe and make some action in my parent page. Here is my codes and it does not work.

In my parent codes:

//(JS PART)
var $currentIFrame = $('#screen'); 
   alert($currentIFrame.contents().find("#abc").type);

//(body part)
  <iframe id="screen" name="screen" width="100%" height="100%" src="test.php">

                   </iframe>

in my iframe files:

//(body part)
<input type="text" id="abc" name="abc">

While, the result is "undefined" instead of "text".

WillDo
  • 123
  • 1
  • 9

4 Answers4

3

you need to use .attr():

  alert($currentIFrame.contents().find("#abc").attr('type'));
Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
2

You need to use attr():

Get the value of an attribute for the first element in the set of matched elements or set one or more attributes for every matched element.

alert($currentIFrame.contents().find("#abc").attr('type'));

EDIT: If the iframe is different domain, you cannot access the contents of it due to Same-origin policy:

Uncaught SecurityError: Failed to read the 'contentDocument' property from 'HTMLIFrameElement': Blocked a frame with origin "http://fiddle.jshell.net" from accessing a frame with origin "http://www.ebay.com". Protocols, domains, and ports must match.

Felix
  • 37,892
  • 8
  • 43
  • 55
  • To access the contents of the iframe. – Felix Mar 06 '14 at 05:26
  • The answer is like, what is the purpose of .find()..? --> it is used to find elements.. *** I am asking find itself enough in this context right..? – Rajaprabhu Aravindasamy Mar 06 '14 at 05:28
  • No you need to use `contents()` to access the iframe – Felix Mar 06 '14 at 05:30
  • This should [help](http://stackoverflow.com/questions/364952/jquery-javascript-accessing-contents-of-an-iframe) or [this](http://stackoverflow.com/questions/8814411/getting-the-html-content-of-an-iframe-using-jquery) felix explaining it – Drixson Oseña Mar 06 '14 at 05:33
  • I made a test but your answers are all not works. Here I use Ebay just for a test, it should return "checkbox" but nothing return: http://jsfiddle.net/PL2Qy/ – WillDo Mar 06 '14 at 05:42
1

try using find

var element = $currentIFrame.find("#abc").attr('type'));
  • I made a test but your answers are all not works. Here I use Ebay just for a test, it should return "checkbox" but nothing return: http://jsfiddle.net/PL2Qy/ – WillDo Mar 06 '14 at 05:43
1

You should pay attention on the 2 factors:

  • 1 - frame should be from the same domain, otherwise you'll be able do nothing;
  • 2 - when you try to get elements inside of the iframe - it must be already loaded.

var frame = $( '#frameSelector' ); frame.load( function(){ var element = frame.contents().find( '.selector' ); });

Sergey Onishchenko
  • 6,943
  • 4
  • 44
  • 51