jQuery and iFrames

In this example I will demonstrate how to access and change data and elements in an iframe from the container document.jQuery is a very useful Javascript library. The “iframe” tag represents an inline frame, in other words an HTML document embedded within another document.

Download the minified (compressed) version of the jQuery library at jQuery.com and save in your web root as “jquery.js”.

First we will create our container web page. Create a new file called “container.html” and put the following text in it.

This gives us a bare-bones web page with an iframe inside it. Now create a file called “iframe.html” that will be loaded inside the iframe. Open the file and put the following text inside.

1
2
3
4
5
6
7
8
9

<html><head></head><body><div id="content">
I am some content within the iframe. Yay!</div></body></html>

The div with an ID of “content” will be our target DOM object. Let’s add two buttons to our container document. When the one is clicked we will read some of the iframe contents. When the other button is clicked we will change some of the iframe contents.

This should be fairly straight forward. What we’ve done is attached some click event handlers to our buttons. When the “Read” button is clicked we access the iframe by ID, access its contents, find the div with an ID of “content” and display its text to the visitor using the “text()” function. The “Write” button goes through the same access chain and then sets the text using the same “text()” function. With this jQuery function if you don’t pass anything into it, it will read. However if you do pass some data into it, it will attempt to write that data to the DOM object.

This demonstrates just another great way the jQuery library can make your Javascript coding easier. Have fun developing!