23/04/2008

jquery and iframes

I needed to select some attributes that were in an iframe today with jquery. The iframe had an id of "preview" so I thought it would be possible to do:

 $('#preview .some_class')

Unfortunately that doesn't work. A quick google turned up nothing so I dug into the source and soon enough it became obvious you can do it like this:

 $('.some_class', $('#preview')[0].content_document)

Only tested in Firefox so far, I've got no idea if it will work in anything else...

Update: I wrote this little function to (hopefully) make this cross browser and a little easier to use:

jQuery.fn.frameselect = function(selector) {
        var oDoc = (this[0].contentWindow || this[0].contentDocument);
        if (oDoc.document) {
            oDoc = oDoc.document;
        }
        return this.pushStack( $(selector, oDoc) );
    }

This means you can write code like:

  $('#id_of_my_iframe').frameselect('div.something_in_the_iframe')

No comments: