Finding child element from iFrame via getElementBy

2019-09-15 11:22发布

I have an iframe on my page, and need to get a child element from it whose ID I have. I'd like to do something like this:

document.getElementById('iframeID').getElementById('child element ID')

I'm open to suggestions on how to accomplish this. Unfortunately I don't have access to jQuery or other handy libraries on this page.

1条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-09-15 11:45

You first need to access the iframe document, here is a cross-browser way to do it:

var ifr=document.getElementById('iframeID');
var doc=ifr.contentWindow||ifr.contentDocument;
if (doc.document) doc=doc.document;

You can then reach the iframe content:

doc.getElementById('child element ID')

Note: this will only work within a same domain, due to the same origin policy.

查看更多
登录 后发表回答