Alex Rivera | Logout

How can I access the contents of an iframe with JavaScript/jQuery?

Asked 2008-12-13T07:20:34.733
863

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?

Edit
Report

2 Answers

1036

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

$("#iFrame").contents().find("#someDiv").removeClass("hidden");

More on the jQuery .contents() method and "how to access an iframe in jQuery"

answered 2009-10-28T18:54:19.867
100

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.

$(document).ready(function(){
    $('#frameID').load(function(){
        $('#frameID').contents().find('body').html('Hey, i`ve changed content of <body>! Yay!!!');
    });
});
answered 2010-04-02T18:27:46.360

Your Answer