4

I want to get .text() of an iframe, but it does not work. The iframe is in the same domain. On one click I load a page to the frame, and on the second I want to display the content in an alert, but I get empty alert.

<html> 
 <head> 
 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> 

 <script type="text/javascript"> 

$(document).ready( function() {
        // load simple paage to the frame
    $("#load").click( function(){

        $("<iframe id='theframe' width='400' // single line
          height='400' src='http://localhost/dummy.html'/>").appendTo('body');

     } );

        // display the content - but I get empty alert
    $('#content').click( function() {
    var content;
    content = $("#theframe").text();
    alert(content);
    });
});

 </script> 
 </head> 
 <body> 

<a id='load' href="#">load</a>
<a id='content' href="#">check content</a>

 </body> 
 </html>
Charles
  • 50,943
  • 13
  • 104
  • 142
Jakub M.
  • 32,471
  • 48
  • 110
  • 179
  • 1
    As far as I know this is not possible, because it's another DOM. The JS inside the iFrame cannot select Elements outside and vice versa. – Johannes Klauß May 15 '12 at 10:05
  • Is this duplicated? http://stackoverflow.com/questions/6316979/selecting-an-element-in-iframe-jquery – Greg May 15 '12 at 12:33

1 Answers1

6

Taken from: Selecting an element in iFrame jQuery

var iframe = $('iframe'); // or some other selector to get the iframe
$('[tokenid=' + token + ']', iframe.contents()).addClass('border');`
Community
  • 1
  • 1
Greg
  • 31,180
  • 18
  • 65
  • 85