sideroxylon
sideroxylon

Reputation: 4416

How to access the contents of an iframe using jQuery or javascript

I have an iframe that loads a page which, when a button is clicked, loads dynamic content including links. I need to change the target of all these links from _blank to _self - but I'm completely stuck on how to get the code to run each time the new content is loaded in the iframe. I've tried lots of options, the latest being to add a click function to the iframe as a trigger to run the code:

$("#myFrame").click(function () {
  $('#myFrame').find('a[target="_blank"]').each(function () {
    $(this).attr('target', '_self');
  });
});

How do find the dynamically generated content and change the link targets once the content has finished loading in the iframe? There is no 'same origin policy' issue, as the page in the iframe is on the same domain.

Thanks.

Upvotes: 0

Views: 1834

Answers (2)

kiran
kiran

Reputation: 305

You can use contents() method

Here is an example :

$("#myiframe").contents().find("#myContent")

Upvotes: 0

Udit Bhardwaj
Udit Bhardwaj

Reputation: 1781

use javaScript to get the DOM of your iframe like this:

var doc=window.frames[ "yourFrameName" ].document

NOTE: Use name not id or class of your frame if you are following above rule to get the DOM of your frame

change this to jquery object

var elem=$(doc);

now bind click event on elem as you are doing in code in your question

elem.click(function () {

 elem.find('a[target="_blank"]').each(function () {

  $(this).attr('target', '_self');
 });

});

Upvotes: 2

Related Questions