问题
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