0

<iframe id="myiframe" src="doc.html">
    <button id="btn1"></button><!-- how to get this id? -->
</iframe>
$('#myiframe').on('click', function () {
    alert(this.id);
});

I want it to alert "btn1".

Oriol
  • 274,082
  • 63
  • 437
  • 513
Andrew Quiros
  • 13
  • 1
  • 3

3 Answers3

0

No. There is no way to do this for security reasons.

The only way to communicate between an iframe and the current page is if the url in the iframe already contains some javascript and updates the iframe url. The iframe then put some data in the url that the page can retrieve.

If the target of the iframe does not belong to you, this is impossible.

Clément Prévost
  • 8,000
  • 2
  • 36
  • 51
0

See jQuery cross domain iframe scripting for a complex workaround which could possibly make this work.

This is not recommended though; the best approach would be to rearchitect the document and try to solve a different problem. For example, you could request the remote content via an ajax call and insert it into your document.

For example, using jQuery.load:

$(".target-element").load("doc.html", null, function() {
    var id = $(".target-element").find("#btn").attr("id");
});
Community
  • 1
  • 1
Tom Rees
  • 681
  • 4
  • 17
-1

this.id isn't valid I think, it would also be technically selecting the wrong id(#myIframe)

you'd want something like this.children().attr('id');

  • `this.id` is fine. Only *issues* are - it is simple and it isn't *jQuery*. – T J Nov 24 '14 at 04:50
  • BTW, you should make *statements* in your *answer*, because this isn't a discussion forum. Discussions goes in **comments**, not via answers. – T J Nov 24 '14 at 04:53