简体   繁体   English

使用 Javascript 访问 iFrame 内的 DOM

[英]Access DOM inside iFrame using Javascript

I am trying to access a DOM element from my main page and want to update the CSS.我试图从我的主页访问一个 DOM 元素并想要更新 CSS。 I use the following;我使用以下内容;

var myIframeContainerEl = $('#myIframeContainerEl');
myIframeContainerEl.contents().find(".required").css("color", "#f0f0f0");

This is not working for some reason.由于某种原因,这不起作用。 While it is able to find "myIframeContainerEl", for some reasons, "myIframeContainerEl.contents()" shows a length of 0. Is the above not the correct way of doing it?虽然它能够找到“myIframeContainerEl”,但由于某些原因,“myIframeContainerEl.contents()”显示的长度为 0。以上不是正确的做法吗?

Also, just to add, I am using this in my Ember project and use it within didTransition hook and inside "afterRender" So the element is present when I am trying to access.另外,只是补充一下,我在我的 Ember 项目中使用它并在 didTransition 钩子和“afterRender”中使用它所以当我尝试访问时该元素存在。

iframe s don't have contents in the document they appear in. But they have a contentDocument property that refers to the document that they do have contents in. You can tell jQuery to look in that document like this: iframe在它们出现的文档中没有内容。但是它们有一个contentDocument属性,该属性引用了它们确实包含内容的文档。您可以告诉 jQuery 在该文档中查找,如下所示:

var frameDocument = $('#myIframeContainerEl')[0].contentDocument;
$(frameDocument).find(".required").css("color", "#f0f0f0");

(Note that this assumes the iframe 's contents are from the same origin, otherwise the Same Origin Policy forbids access unless CORS or similar is used.) (请注意,这假设iframe的内容来自同一来源,否则除非使用CORS或类似内容,否则同源政策禁止访问。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM