How to access iframe element from its child element

别来无恙 提交于 2020-01-06 03:47:05

问题


I have a requirement to access iframe element object from its child element in a event handler function.

An example would be like this.

function callback(ev) {
  //get the event target element
  var targetElement = ev.target;

  //get the document object of the target element
  var doc = targetElement.ownerDocument;

  //Question: how to get to the doc's iframe object
  // I tried these properties below, both returns null
  var ifrmEle = doc.parentElement;
  var ifrmEle = doc.parentNode;
}

Say the targetElement is the body element in the above example, So my question is how could I access the iframe element owning the body element?

Thanks for your expertise.


回答1:


There's no convenient property that would give you that information.

The closest you would do would be to loop over all the frames in the parent document until you found one containing the same document.

Parent document

<!DOCTYPE html>
<meta charset="utf-8">
<title>Iframe Parent</title>
<h1>Iframe Parent</h1>
<iframe src="iframe.html" name="one"></iframe>
<iframe src="iframe.html" name="two"></iframe>
<iframe src="iframe.html" name="three"></iframe>
<iframe src="iframe.html" name="four"></iframe>

Child document

<!DOCTYPE html>
<meta charset="utf-8">
<title>Iframe</title>
<h1>Iframe</h1>
<p>This document is in a frame named <span>?</span>.</p>
<script>
    parent.document
    .querySelectorAll('iframe, frame')
    .forEach(frame => {
        if(frame.contentWindow.document === document) {
            document.querySelector('span').textContent = frame.name;
        }
    });
</script>


来源:https://stackoverflow.com/questions/51590417/how-to-access-iframe-element-from-its-child-element

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