javascript 如何从父窗口访问 iframe 中存在的元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8676478/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 04:11:45  来源:igfitidea点击:

How to access element present inside a iframe from parent window?

javascripthtmliframe

提问by user1122379

I have an iframe. I want to access a table which present inside iframe.I want to access it from parent window of iframe. I have written JS like

我有一个 iframe。我想访问 iframe 中存在的表。我想从 iframe 的父窗口访问它。我写过 JS 之类的

Document.getElementById("table Id");

But the result come null. What is the process to get it? thanks

但结果为空。获得它的过程是什么?谢谢

回答by sushil bharwani


x=document.getElementById("iFrameId");
x.contentDocument.getElementById("tableId");

if you can use jQuery i guess it will work across browsers

如果您可以使用 jQuery,我想它可以跨浏览器工作

$("#iFrameId").contents().find("#tableId")

$("#iFrameId").contents().find("#tableId")

回答by Adam Rackis

You have to select the element from the iFrame's document. Per Juan's comment, check against both the name, and id of the iFrame

您必须从 iFrame 的文档中选择元素。根据 Juan 的评论,检查 iFrame 的名称和 ID

var targetFrame = window.frames["nameOfIFrame"] || window.frames["iFrameId"];
targetFrame.document.getElementById("tableId");

EDIT

编辑

I just tested this with the following:

我刚刚用以下内容对此进行了测试:

window.frames["fName"].document.getElementById("Adam").innerHTML

in the Chrome console, and it output the html of the Adamdiv from within my iframe.

在 Chrome 控制台中,它Adam从我的 iframe 中输出div的 html 。