使用JavaScript访问iframe和body标记内的元素
我正在编写一个GreaseMonkey脚本,它修改具有特定ID的元素的属性,但是由于非传统HTML层次结构,访问它时遇到一些问题。以下是相关的HTML:使用JavaScript访问iframe和body标记内的元素,javascript,html,dom,iframe,cross-browser,Javascript,Html,Dom,Iframe,Cross Browser,我正在编写一个GreaseMonkey脚本,它修改具有特定ID的元素的属性,但是由于非传统HTML层次结构,访问它时遇到一些问题。以下是相关的HTML: <body> ... <iframe id="iframeID"> <html> ... <body id="bodyID" attribute="value"> ... </bo
<body>
...
<iframe id="iframeID">
<html>
...
<body id="bodyID" attribute="value">
...
</body>
...
</html>
</iframe>
...
</body>
虽然这在Firefox中运行良好,但Chrome告诉我无法设置
null
的属性,这表明它找不到任何id为bodyID
的元素。如何以跨浏览器友好的方式修改此属性?首先需要提取
的文档:
document.getElementById('iframeID').contentDocument
.getElementById('bodyID').setAttribute("attribute","value");
document.getElementById('iframeID').contentDocument.body.setAttribute("attribute","value");
顺便说一句,如果您想要获得
节点,您不需要提供id或类似的信息,只需:
document.body
在您的情况下,它是
的文档:
document.getElementById('iframeID').contentDocument
.getElementById('bodyID').setAttribute("attribute","value");
document.getElementById('iframeID').contentDocument.body.setAttribute("attribute","value");
简单多了。。。不是吗?在我看来,最好的方法是监听iFrame触发的
load
事件,然后根据需要查看iFrame DOM。这保证了在需要时可以使用iFrame DOM并拍摄一段时间
$('#iframeID').on('load', function ()
{
alert('loaded'); // iFrame successfully loaded
var iFrameDoc = $('#iframeID')[0].contentDocument; // Get the iFrame document
$('body', iFrameDoc).attr('attribute', 'new value'); // Get the 'body' in the iFrame document and set 'attribute' to 'new value'
});
您是否尝试过
window.frames
?(doc:)@drderp虽然我认为这会起作用,但与gdoron的解决方案相比,代码会包含不必要的混乱。gdoron在我发布我的解决方案后立即发布了他的解决方案;我同意你的看法。请参阅我关于演示的更新。
+jQuery标签在哪里?请阅读我关于
@gdoron的评论,在您的应用程序中添加jQuery。如果由于跨域策略,iFrame和iFrame容器具有不同的域,则此操作将不起作用。不确定关于jQuery您想说什么。您的答案与跨域策略有相同的问题。