We have a way to Traversing down the DOM through iframes to #btn1 we can do this by $('#iframe1').contents().find('#iframe2').contents().find('#btn1')
I am struggling to traverse moving up the DOM from #btn1 to outside #iframe2
Following code gives me []. Consider btnElement to be jquery#btn object
`btnElement.closest('iframe')`
Neither does this works
btnElement.parent().parent().parent()
Is there a way to access Dom outside iframe2 from btn1??
Note : All iframes belongs to the same origin. Cross origin is not the concern to me
You can't traverse to it, no; the DOM jQuery works with is rooted in the iframe's window.
But that window object has a parent
property which refers to the parent window. So you can use that to access things in the parent window.
If the parent window also has jQuery loaded, you can use it like this: parent.$("selector")
.
If the parent window doesn't have jQuery loaded but the iframe does, you can usually look things up in the parent like this: $(parent.document).find("selector")
, but other uses of jQuery may be squirrelly, best if possible to use the instance of jQuery from the window in which it's loaded.
(You can only do this if the frame and its parent are loaded from the same origin.)
Re your comment:
Only thing given to me is. jquery object of btn1. How can I find out its parent iframe element. ?
I want to access DOM outside this iframe Say for eg I want to know current iframe's parent div
I don't believe there's any direct way to do that, no, you have to hunting: The button element inside the jQuery object (eg, btn1[0]
) has a property called ownerDocument
, which will be === (theWindowThatContainsIt).document
. iframe elements have a contentDocument
property which refers to the same thing. So you use parent
to get the parent window, then find all the iframe
s in it, and select the one that has .contentDocument === btn[0].ownerDocument
:
var btn1 = $("#btn");
var doc = btn1[0].ownerDocument;
var iframe = $(parent.document).find("iframe").filter(function() {
return this.contentDocument === doc;
});
if (iframe.length) {
// We have the `iframe` element. To get its parent, we'd use
// `iframe.parent()`. Let's give it a green border:
iframe.parent().css("border", "1px solid green");
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.