jQuery/JavaScript: accessing contents of an iframe – Dev

The best answers to the question “jQuery/JavaScript: accessing contents of an iframe” in the category Dev.


I would like to manipulate the HTML inside an iframe using jQuery.

I thought I’d be able to do this by setting the context of the jQuery function to be the document of the iframe, something like:

$(function(){ //document ready
    $('some selector', frames['nameOfMyIframe'].document).doStuff()

However this doesn’t seem to work. A bit of inspection shows me that the variables in frames['nameOfMyIframe'] are undefined unless I wait a while for the iframe to load. However, when the iframe loads the variables are not accessible (I get permission denied-type errors).

Does anyone know of a work-around to this?


I think what you are doing is subject to the same origin policy. This should be the reason why you are getting permission denied type errors.


If the <iframe> is from the same domain, the elements are easily accessible as




If the iframe src is from another domain you can still do it. You need to read the external page into PHP and echo it from your domain. Like this:


    $URL = "http://external.com";

    $domain = file_get_contents($URL);

    echo $domain;

Then something like this:


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


    cleanit = setInterval ( "cleaning()", 500 );

function cleaning(){
    if($('#frametest').contents().find('.selector').html() == "somthing"){
        $('#selector').contents().find('.Link').html('ideate tech');


<iframe name="frametest" id="frametest" src="http://yourdomain.com/iframe_page.php" ></iframe>

The above is an example of how to edit an external page through an iframe without the access denied etc…


You could use .contents() method of jQuery.

The .contents() method can also be used to get the content document of an iframe, if the iframe is on the same domain as the main page.

        $('#frameID').contents().find('body').html('Hey, i`ve changed content of <body>! Yay!!!');