Howto: selecting an iframe with jQuery

Von in javascript, jquery, netzthetik

Recent­ly I had to fetch a DOM ele­ment of an inli­ne frame via Java­Script, name­ly a text­area. The job was to append some cha­rac­ters to an exis­ting text dyna­mi­cal­ly. What looks like shoo­ting fish in a bar­rel puz­zled me some hours. Read this arti­cle to figu­re out that pie­ce of cake.
(deut­sche Ver­si­on die­ses Arti­kels: “jQue­ry und iframes”)

By way of illus­tra­ti­on I use the well known Java­Script WYSIWYG-​Editor tinyMCE. This par­ti­cu­lar edi­tor doesn’t insert a text­area, it actual­ly fits in an iframe. Let’s have a look at the DOM:

<iframe id="content_ifr" frameborder="0" [...]>
    <html>
        <head xmlns="http://www.w3.org/1999/xhtml">
        [...]
        <body id="tinymce" class="mceContentBody" [...]>
        <p>[...]</p>
        [...]

Just try to select the text­area (respec­tively the body) this way:

$('#tinymce');

It won’t work, becau­se the iframe is equip­ped with its own HTML-​architecture with uni­que docu­ment object model.

The good news is that this DOM is acces­si­ble via JavaScript:

window.frames['name_of_iframe']
    .document.getElementById('name_of_id');

Using the frame­work jQue­ry it might look like…

$('#id_of_iframe').contents().find('#id');

or accord­ing to our examp­le with the tinyMCE editor:

$('#content_ifr').contents().find('#tinymce').html();

The func­tion “con­tents()” has been espe­ci­al­ly desi­gned for selec­ting iframes. We can’t access the selec­tor twice for chai­ning, but using “find()” for grab­bing an id or class wit­hin the iframe does the trick.

Share on LinkedInShare on Redditshare on TumblrShare on StumbleUponDigg thisShare on FacebookGoogle+Tweet about this on TwitterEmail to someone