Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to select an iframe from itself with jquery

Tags:

jquery

iframe

I need to select an iframe with an jquery query inside the same iframe. However, I don't want to assign the iframe a unique id and use

$('#'+self.name,top.document)

(which i saw somewhere). Is there any relative way to do this (something with $(this) and traversing ??!?)

Everything is on the same server, there is no xss.

like image 510
Rado Avatar asked Nov 27 '22 08:11

Rado


2 Answers

If you have only one iFrame on your site it's easy. Just use this selector

 $('iframe', parent.document)

If you have more then one it gets more complicated. iFrame document doesn't have a clue in which of the main page iframes it was loaded so there is no easy way of selecting parent iframe with the selector. If you however know the parent id, name, class or even iframe source url you can use that information to modify the selector above to only match iframe that you want. You could also match a iframe you need if you know its index on the main page.

 // iframe with MyClass class
 $('iframe.MyClass', parent.document);

 // iframe with MyId id
 $('iframe#MyId', parent.document);
 // even better since id is unique
 $('#MyId', parent.document);

 // iframe with myname name
 $('iframe[name=myname]', parent.document);

 // iframe with specific src
 $('iframe[src=/path/to/iframe/source]', parent.document);

 // second iframe (index is starting from 0)
 $('iframe:eq(1)', parent.document); 
like image 175
RaYell Avatar answered Dec 05 '22 17:12

RaYell


To select the second iframe it has to be:

second iframe (index is starting from 0)
$('iframe:eq(1)', parent.document);
like image 32
karl Avatar answered Dec 05 '22 18:12

karl