2012-06-30 50 views
4

我在写一个GreaseMonkey脚本,它修改了具有特定ID的元素的属性,但由于非传统的HTML层次结构,我在访问它时遇到了一些问题。下面是相关的HTML:使用JavaScript访问iframe和body标签内的元素

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

其中attribute是我试图修改的属性。

起初,并没有意识到我有iframe和嵌套body标签的工作,我尝试这样做:

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

虽然这在Firefox中工作得很好,Chrome的告诉我,我不能设置属性null,表明它找不到任何ID为bodyID的元素。如何以跨浏览器友好的方式修改此属性?

+0

你试过'window.frames'吗? (doc:https://developer.mozilla.org/en/DOM/window.frames) –

+0

@drderp虽然我认为这样会工作,但与gdoron的解决方案相比,代码将包含不必要的混乱。 – Sonic42

+2

gdoron在我发布我的帖子后发布了他的解决方案;我对此表示同意。 –

回答

8

首先需要拉的文件:

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

Live DEMO

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

document.body 

在你的情况,这是的文件:

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

简单得多...不是吗?

+0

非常感谢您的帮助! – Sonic42

1

要做到这一点,IMO最好的办法是听ifFrame触发的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' 
}); 
+1

jQuery标签在哪里?并阅读我对'' – gdoron

+0

@gdoron的评论,在您的中添加jQuery。如果iFrame和iFrame容器由于跨域策略而具有不同的域,这将不起作用。 – Gezim

+0

不确定你对jQuery的意思。并且您的答案与跨域政策有同样的问题。 – gdoron