繁体   English   中英

使用JavaScript访问iframe和body标签内的元素

[英]Accessing Elements Inside iframe and body Tags with JavaScript

我正在编写一个GreaseMonkey脚本,用于修改具有特定ID的元素的属性,但由于非传统的HTML层次结构,我在访问它时遇到了一些问题。 这是相关的HTML:

<body>
...
    <iframe id="iframeID">
        <html>
        ...
            <body id="bodyID" attribute="value">
            ...
            </body>
        ...
        </html>
    </iframe>
...
</body> 

where attribute是我试图修改的属性。

起初,没有意识到我正在使用iframe和嵌套的body标签,我试过这个:

document.getElementById('bodyID').setAttribute("attribute","value")

虽然这在Firefox中运行良好,但Chrome告诉我,我无法设置null属性,这表明它找不到具有id bodyID任何元素。 如何以跨浏览器友好的方式修改此属性?

您首先需要提取<iframe>的文档:

document.getElementById('iframeID').contentDocument
.getElementById('bodyID').setAttribute("attribute","value");

现场演示

顺便说一句,如果你想获得<body>节点,你不需要提供id或类似的东西,只需:

document.body

在您的情况下,它是<iframe>的文档:

document.getElementById('iframeID').contentDocument.body.setAttribute("attribute","value");

简单得多......不是吗?

IMO的最佳方法是监听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'
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM