Ben Pearce
Ben Pearce

Reputation: 7094

Styling iframe contents from parent frame css

I have a page with an embedded iframe and I need to style elements that are displayed within the iframe. The catch is I can't edit the iframe (I think it's same origin but I'm not sure), so I need to style the iframe contents via code in the parent frame. I have attempted to do this through selectors with no success.

Ex:

<html>
   <body>
      <iframe id="frame">
         <div id="target">target</div>
      </iframe>
   </body>
</html>

CSS Approach:

#frame #target{
   background:red;
}

jQuery Approach:

$("#frame #target").css({'background':'red'});

Upvotes: 2

Views: 4175

Answers (2)

Carlos Calla
Carlos Calla

Reputation: 6716

What you are using is not working because the iFrame takes some time to load after your parent page is loaded. So the CSS and JS of your parent page is loaded before the iFrame is loaded, therefore styles and js are not applied to the iFrame.

You can use

$('#frame-target').contents().find('#target-inside').css({'background': 'red'});

to achieve this. I don't actually remember if this waits for the iFrame to load. If this doesn't work you can wait until it is loaded with he load event or set a timeout of 1 second before you apply this.

Upvotes: 0

emmanuel
emmanuel

Reputation: 9615

You could use .contents() function:

$('frame').contents().find('#target').css({'background':'red'});

Upvotes: 3

Related Questions