2012-06-30 49 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