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

Son*_*c42 4 html javascript iframe dom cross-browser

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

<body>
...
    <iframe id="iframeID">
        <html>
        ...
            <body id="bodyID" attribute="value">
            ...
            </body>
        ...
        </html>
    </iframe>
...
</body> 
Run Code Online (Sandbox Code Playgroud)

attribute我试图修改的属性在哪里.

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

document.getElementById('bodyID').setAttribute("attribute","value")
Run Code Online (Sandbox Code Playgroud)

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

gdo*_*ica 9

您首先需要提取以下文件<iframe>:

document.getElementById('iframeID').contentDocument
.getElementById('bodyID').setAttribute("attribute","value");
Run Code Online (Sandbox Code Playgroud)

现场演示

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

document.body
Run Code Online (Sandbox Code Playgroud)

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

document.getElementById('iframeID').contentDocument.body.setAttribute("attribute","value");
Run Code Online (Sandbox Code Playgroud)

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