2

Let's say I have an iframe page (iframe.html). Inside this page, I have a script $(body) or $(document). Now I wanted to understand what does it represent ?

Does it refer to iframes body or the main page body ? If it represnts the main page, how do I make it refer to the iframe ?

Diana
  • 435
  • 1
  • 11
  • 19

4 Answers4

5

To find element withing iframe try this

$("iframeSelector").contents().find("#element_in_iframe").click(function(e){ 
   alert(1); 
 });
ShankarSangoli
  • 69,612
  • 13
  • 93
  • 124
3

$('body') and document refer to those of the iframe's own document.

  • Within the encapsulating page, use this to access the iframe contents with jQuery selectors.

  • Within the iframe, window.parent may refer to the encapsulating page.

Community
  • 1
  • 1
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
0

If you are inside the iframe:

$(body) and $(document) will refer to the document contained within the iframe, and will typically be ignorant of the parent page.

If you need to access the outer page from within the iframe:

You can use window.parent to access the page that contains the iframe if necessary.

Rion Williams
  • 74,820
  • 37
  • 200
  • 327
0

It refers to the body in side your IFRAME. jQuery will always work in the context of the current (first parent) document. If you want to specify a different context, that is when you use jquery's context arguments.

http://api.jquery.com/jQuery/#jQuery1

jQuery( selector, [context] ) selector: A string containing a selector expression context: A DOM Element, Document, or jQuery to use as context

So $('body') refers to the document inside your IFRAME and can be thought to be implicitly doing: $('body', document); To get the document of the parent frame you would have to do something like $('body', parent.document);. This would of course be subject to cross-frame restrictions, depending on how you're doing this.

John Hoven
  • 4,085
  • 2
  • 28
  • 32