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" [...]>
        <head xmlns="">
        <body id="tinymce" class="mceContentBody" [...]>

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


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 Java­Script:


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


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


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.