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.

1
2
3
4
5
6
7
8
<html>
<head>
    <script type="text/javascript" src="jquery.js"></script>
</head>
<body>
    <iframe name="someiframe" src="iframe.html"></iframe>
</body>
</html>

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.

Update your “container.html” page to look like this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<html>
<head>
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            $('#readBtn').click(function(){
                alert($("#iframe").contents().find("#content").text());
            });
            $('#writeBtn').click(function(){
                $("#iframe").contents().find("#content").text('this content has changed!');
                alert('The iframe contents have been changed!');
            });
        });
    </script>
</head>
<body>
    <button id="readBtn">Read</button><br />
    <button id="writeBtn">Write</button><br />
    <iframe style="width:500px;height:400px;" id="iframe" src="iframe.html"></iframe>
</body>
</html>

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!