Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find a div inside of an iframe

Tags:

jquery

iframe

I am trying to use jquery to find a div inside an iframe. Is there a better way than the one I'm using below?

$('#Iframe').contents().find('#MyDiv')

function atmslidein(){
   $("#customer").ready(function(){         
       if($('#customer').attr('src')=='ATM.html')
       {
          $('#customer').contents().find('.atm_page').css('margin-left', '270px'); 
          $('#customer').contents().find('.tele').css('display', 'none');
       }
    })
}

I've tried almost a week to make this work:

$('#Iframe').contents().find('#MyDiv')

That is why I tried another way to access the iframe's div.


Anyway I found something that the iframe document should have and only then the above function works properly:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

My problem is solved, thanks. But could someone explain why this is necessary?

like image 319
rajaishbt Avatar asked Jan 05 '11 09:01

rajaishbt


People also ask

Can you put a div inside an iframe?

Approach 1: For adding additional div's in an iframe, you need to use a wrapper div, that wraps the contents of your intended div and the iframe into one unit. This way you can display the contents of your div along with the iframe embedding to the document/webpage.

What is #document in iframe?

Definition and Usage. The contentDocument property returns the Document object generated by a frame or iframe element. This property can be used in the host window to access the Document object that belongs to a frame or iframe element.


2 Answers

I don't think the jQuery can access the contentWindow/Document's content in that way. In the past, I've had to do this:

$('#iframe').each(function() {
    $('#MyDiv', this.contentWindow.document||this.contentDocument);
});

** Note that this.contentWindow||this.contentDocument is required to work correctly across IE and most other browsers. Once you get the content window, you need to select the document. Then you can use jQuery to manipulate or traverse the DOM, but only if the iframe's source is in the same domain.

** Updated to fix error where we don't specify the document after we get the contentWindow/Document.

like image 69
moribvndvs Avatar answered Oct 23 '22 03:10

moribvndvs


This will only work if the Iframe source is in the same domain as your page, if not the browser wont allow it for security reasons

like image 43
Luis Avatar answered Oct 23 '22 04:10

Luis