select the immediate parent element of an iframe from the iframe

泪湿孤枕 提交于 2019-12-22 20:42:34

问题


I have the markup below:

<html>
    <body>
        <div class="aaa"></div>
        <div class="aaa"></div>
        <div class="aaa">
            <iframe>
                <form id="myform">

                </form>
            </iframe>
        </div>
        <div class="aaa"></div>
    </body>
</html>

On loading the iframe, it contains the form '#myform'. Upon submission of the form, I need to run a certain callback based on the div.aaa that is the immediate parent of the iframe.

Any solution based on parent.document cannot help me much, since I do not know the ID of the div.aaa.

What I'd like to do is something like $('#myform').closest('div.aaa'), but, of course, this fails because any element beyond the iframe window itself cannot be accessed in this fashion.

How can I best access this iframe's immediate parent div, which is actually an element in it's parent document?

Both parent and iframe are of same origin.


回答1:


You can jump up to the parent window and look for specific iframe in parent document by matching frame element contentWindow to known window inside the iframe

Something like:

$(window.parent.document).find('iframe').filter(function() {
  return this.contentWindow === window;
}).parent().doSomething()

DEMO




回答2:


I would recommend to use .closest('.aaa'). But if you could assign a unique identifier you may use .parent('.uniq_selector') that is a bit more performant.



来源:https://stackoverflow.com/questions/53239431/select-the-immediate-parent-element-of-an-iframe-from-the-iframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!