Get element from within an iFrame

2018-12-31 04:20发布

How do you get a <div> from within an <iframe>?

6条回答
浮光初槿花落
2楼-- · 2018-12-31 05:00

Do not forget to access iframe after it is loaded. Old but reliable way without jQuery:

<iframe src="samedomain.com/page.htm" id="iframe" onload="access()"></iframe>

<script>
function access() {
   var iframe = document.getElementById("iframe");
   var innerDoc = iframe.contentDocument || iframe.contentWindow.document;
   console.log(innerDoc.body);
}
</script>
查看更多
美炸的是我
3楼-- · 2018-12-31 05:01

Below code will help you to find out iframe data.

let iframe = document.getElementById('frameId');
let innerDoc = iframe.contentDocument || iframe.contentWindow.document;
查看更多
姐姐魅力值爆表
4楼-- · 2018-12-31 05:03

None of the other answers were working for me. I ended up creating a function within my iframe that returns the object I was looking for:

function getElementWithinIframe() {
    return document.getElementById('copy-sheet-form');
}

Then you call that function like so to retrieve the element:

var el = document.getElementById("iframeId").contentWindow.functionNameToCall();
查看更多
ら面具成の殇う
5楼-- · 2018-12-31 05:13
var iframe = document.getElementById('iframeId');
var innerDoc = (iframe.contentDocument) ? iframe.contentDocument : iframe.contentWindow.document;

You could more simply write:

var iframe = document.getElementById('iframeId');
var innerDoc = iframe.contentDocument || iframe.contentWindow.document;

and the first valid inner doc will be returned.

Once you get the inner doc, you can just access its internals the same way as you would access any element on your current page. (innerDoc.getElementById...etc.)

IMPORTANT: Make sure that the iframe is on the same domain, otherwise you can't get access to its internals. That would be cross-site scripting.

查看更多
泪湿衣
6楼-- · 2018-12-31 05:13
window.parent.document.getElementById("framekit").contentWindow.CallYourFunction('pass your value')

CallYourFunction() is function inside page and that function action on it

查看更多
临风纵饮
7楼-- · 2018-12-31 05:19

Above answers gave good solutions using Javscript. Here is a simple jQuery solution:

$('#iframeId').contents().find('div')

The trick here is jQuery's .contents() method, unlike .children() which can only get HTML elements, .contents() can get both text nodes and HTML elements. That's why one can get document contents of an iframe by using it.

Further reading about jQuery .contents(): .contents()

Note that the iframe and page have to be on the same domain.

查看更多
登录 后发表回答