How to add a click event to p elements in iframe (using jQuery)

How to add a click event to <p> elements in iframe (using jQuery)

<iframe frameborder="0" id="oframe" src="iframe.html" width="100%" name="oframe">



There's a special jQuery function that does that: .contents(). See the example for how it's works.


Your best best bet is to invoke the iframe AS LONG AS it's part of your domain.


            window.MyMethod = function()

And then use


To invoke that function.

another way is to access the iframe via window.frames.

<iframe name="myIframe" src="iframe.html"/>

and the javascript

child_frame = window.frames['myIframe'].document;
    alert('This click as bound via the parent frame')

That should work fine.


By giving a reference to the IFrame document as the second parameter to jQuery, which is the context:

jQuery("p", document.frames["oframe"].document).click(...);

To access any element from within an iframe, a simple JavaScript approach is as follows:

var iframe = document.getElementById("iframe");
var iframeDoc = iframe.contentDocument || iframe.contentWindow;
// Get HTML element
var iframeHtml = iframeDoc.getElementsByTagName("html")[0];

Now you can select any element using this html element


Now, you can bind any event you want to this element. Hope this helps. Sorry for incorrect English.


Wanted to add this, as a complete, copy-paste solution (works on Firefox and Chrome). Sometimes it is easy to miss to remember to call the event after the document, and so the iframe, is fully loaded:

$('#iframe').on('load', function() {
    $('#iframe').contents().find('#div-in-iframe').click(function() {
        // ...

The iframe must be on the same domain for this to work.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.