[英]getting the contents of a div tag with class
我正在嘗試從父窗口讀取包裝在div標簽中的子IFrame的特定內容。 我在用
detailsValue = window.frames['myIframe'].document.getElementById('result').innerHTML;
這樣,我就可以訪問該框架的全部內容。 但是我只需要訪問該內容的一部分。 問題是包裝我要查找的內容的div僅包含類,而沒有ID。
<div class="watINeed"> <table class="details"> </table> </div>
我無法訪問表格形式的內容(沒有ID,只有類)。
任何幫助。
Edit1:我需要訪問表的內容以檢查char長度以及該內容中存在的一些html標簽。
您可以使用純Javascript(如Notulysses所述)來執行此操作:
window.frames['myIframe'].document.querySelector('.watINeed .details')
或通過將iframe的document
指定為$
上下文來使用jQuery(因為您將jquery賦予$
ad):
$(".watINeed .details", window.frames['myIframe'].document)
在后一種情況下,您具有功能齊全的jQuery對象。
請注意,無論哪種情況,iframe的文檔都必須位於同一域中,否則會遇到跨源問題。
經過jQuery 2.0.x測試
如果在包含頁面的頁面加載期間運行選擇器,則必須先訪問iframe的load
事件,然后才能訪問其內容:
$(window.frames['myIframe']).on("load", function(){
// above query here
});
如果您正在尋找原始Javascript,並且您的目標div
是啟動選擇器的直接子代,那么這很簡單
var detailsValue = window.frames['myIframe'].document.getElementById('result').innerHTML;
var target;
for(var i = 0; i< detailsValue.children.lenght; i ++){
if(detailsValue.children[i].getAttribute('class')== 'watINeed'){
target = detailsValue.children[i] ;
}
}
否則,必須編寫一個遞歸方法來廢棄所有結構子對象
如我上面所寫,可以使用以下方法完成:
document.querySelectorAll(".className")[0] or $(".className")[0]
它們基本上都與返回節點列表相同,並且[0]
只是意味着從列表中獲取第一個結果。
有兩件事要注意:
iframe會異步加載內容,因此在執行查詢時,最有可能尚未加載您要搜索的元素。 在DOM加載后執行代碼還不夠 。
解決方案就是將您的代碼放在一個塊中,該塊將在所有異步內容加載完畢后執行:
在window.onload =函數(){\n window.frames [ 'myIframe'] document.querySelectorAll( “watINeed”。)[0];\n }
或jQuery替代品:
$(窗口).load(函數(){\n window.frames [ 'myIframe'] document.querySelectorAll( “watINeed”。)[0];\n });
第二件事是,根據此處的頁面,您可以使用contentWindow.document
訪問iframe的文檔:
在window.onload =函數(){\n window.frames [ 'myIframe'] contentWindow.document.querySelectorAll( “watINeed”。)[0];\n }
或jQuery替代品:
$(窗口).load(函數(){\n window.frames [ 'myIframe'] contentWindow.document.querySelectorAll( “watINeed”。)[0];\n });
現場示例: 小提琴
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.