Hamid Talebi
Hamid Talebi

Reputation: 1318

Get parent of clicked tag inside of iframe

I've an iframe that contain an HTML page.Now I want to get class of the parent item that clicked.
this is my ifram:

<iframe src="//example.com" id="frame" ></iframe>  

this is css:

#frame{  width:380px;  height:420px;}  

this is my script:

$(document).ready(function() {
  var iframe = document.getElementById('frame');
  var innerDoc = iframe.contentDocument || iframe.contentWindow.document.body;
  $(innerDoc).on('click', function(e) {
    var thisID = ((e.target).id);
    alert(thisID);
    alert(innerDoc.getElementById(thisID));


    $(thisID).click(function() {
      var Allclassnames = $(thisID).parent();
      console.log(Allclassnames);
    });
  });
});

but it return the item was clicked only.how to fix it?

Demo:DEMO

NOTE:these are in a same domain.maybe below DEMO not worked for this reason.but I'm sure that my HTML is inside of the same domain with my web site. thank you.

Upvotes: 1

Views: 164

Answers (2)

Vinay
Vinay

Reputation: 7676

Add sandbox attributes to the iframe

<iframe src="/example.html" id="frame" sandbox="allow-scripts allow-same-origin"></iframe> 

Change the script to

<script>
$('#frame').load(function() {
  $('#frame').contents().on('click', function(e) {  
    var thisID = ((e.target).id);
    alert(thisID); 
    alert($('#'+thisID,this));
      $('#'+thisID,this).click(function() {
        var Allclassnames = $(this).parent();
        console.log(Allclassnames); 
      });
  });
});
</script>

Make sure that every element in frame doc. have some id or else the alert() may throw an error.

To see the console message of iframe you need to change the scope from the scope dropdown , it's in console tab besides the filter icon in the chrome developer tools.

Upvotes: 1

Josh
Josh

Reputation: 3288

You cannot interact with the contents of an iframe unless it is on the same domain as the parent document.

See:
https://en.wikipedia.org/wiki/Same-origin_policy

Upvotes: 0

Related Questions