访问元素在iframe和body标签使用JavaScript [英] Accessing Elements Inside iframe and body Tags with JavaScript

查看:302
本文介绍了访问元素在iframe和body标签使用JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm writing a GreaseMonkey script that modifies an attribute of an element with a specific ID, but I'm having some problems accessing it due to a nontraditional HTML hierarchy. Here's the relevant HTML:

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

其中属性 m尝试修改。

最初,没有意识到我正在使用 iframe 和嵌套 body 标记,我尝试这样:

At first, not realizing I was working with an iframe and a nested body tag, I tried this:

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

我不能设置 null 的属性,表明它找不到id bodyID 的任何元素。如何以跨浏览器友好的方式修改此属性?

While this worked fine in Firefox, Chrome tells me that I can't set the attribute of null, suggesting that it cannot find any elements with the id bodyID. How can I modify this attribute in a cross-browser friendly fashion?

推荐答案

您首先需要拉取< c $ c>< iframe> :

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

现场DEMO

BTW,如果您想获得< body> 节点,你不需要给id或类似的东西,简单:

BTW, if you want to get the <body> node, you don't need to give id or something like that, simply:

document.body

在这种情况下,它是< iframe>

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

很简单...不是吗?

这篇关于访问元素在iframe和body标签使用JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆