简体   繁体   中英

Access DOM inside iFrame using Javascript

I am trying to access a DOM element from my main page and want to update the 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?

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.

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:

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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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