fifth fifth - 1 month ago 5
HTML Question

Modifying the HTML content of an iframe using jQuery

I have an html page that has an iframe with the src attribute pointing to another html page which already has some content in it.

parent.html

<body>
<iframe src="child.html"></iframe>
</body>


child.html

<body>
<p>test1</p>
</body>


parent.html also has a jquery function that tries to append a paragraph to the body of child.html:

$(function(){
var $iframe = $("iframe");
$iframe.ready(function(){
$iframe.contents().find("body").append("<p>test2</p>");
});

});


The problem is that the function is not working, the paragraph is not being added. The interesting part is that if I remove "child.html" from the src attribute of the iframe, the paragraph is being added into a blank html page.

Is it not possible to modify the content of an html document from an iframe (when the document already contains a number of elements)?

Also, there isn't any problem with the cross-domain policy.

Thanks in advance.

Answer

It looks like the code is executing before the iframe contents has actually loaded. Try this code:

$(document).ready(function(){
    var $iframe = $("iframe");
    $iframe.on('load', (function(){
        $iframe.contents().find("body").append("<p>test2</p>");
    });
});