Selecting an element in iFrame jQuery

cycero picture cycero · Jun 11, 2011 · Viewed 211.8k times · Source

In our application, we parse a web page and load it into another page in an iFrame. All the elements in that loaded page have their tokenid-s. I need to select the elements by those tokenid-s. Means - I click on an element on the main page and select corresponding element in the page in the iFrame. With the help of jQuery I'm doing it in the following way:

function selectElement(token) {
     $('[tokenid=' + token + ']').addClass('border'); 
}

However with this function I can select the elements in the current page only, not in the iFrame. Could anybody tell me how can I select the elements in the loaded iFrame?

Thanks.

Answer

Darin Dimitrov picture Darin Dimitrov · Jun 11, 2011
var iframe = $('iframe'); // or some other selector to get the iframe
$('[tokenid=' + token + ']', iframe.contents()).addClass('border');

Also note that if the src of this iframe is pointing to a different domain, due to security reasons, you will not be able to access the contents of this iframe in javascript.