0

I have an element inside an iframe, such as the body of the iframe, and from this element I need to access all the parents of the specific iframe which this element belongs to. There may be more than one iframe in the document and I need only the parents of the specific iframe, filtered by a selector (such as class name).

If the element would not have been inside an iframe, I could do just element.parents('.class-name');. I need to check if this parent contains a specific descendant (filtered by a selector such as class name).

If the given element is not inside an iframe, just return its parents without any error message.

Uri
  • 2,992
  • 8
  • 43
  • 86
  • if you do a $("xxx").closest("yyy") inside an iframe it should only find you the "yyy" inside the iframe, it won't check the parent window. – artm Sep 28 '14 at 12:05
  • 1
    because it's a frame you will have to get the `window.parent` which will be main page window and work from there to locate the iframe element – charlietfl Sep 28 '14 at 12:07
  • [Some info](http://stackoverflow.com/a/24096958/1169519) about how to access `(i)frame`s. – Teemu Sep 28 '14 at 12:15

2 Answers2

0

I found a solution, I'm not sure if it's ideal but here it is:

var $element = jQuery(element);
var element_frame_element = $element[0].ownerDocument.defaultView.frameElement;
var element_parent = ((element_frame_element === null) ? $element : jQuery(element_frame_element)).parents('.class-name')
Uri
  • 2,992
  • 8
  • 43
  • 86
0

Something like this: window.parent.$('.className')

Deepak Biswal
  • 4,280
  • 2
  • 20
  • 37