Imnotapotato
Imnotapotato

Reputation: 5828

How to apply CSS to iframe using jQuery?

How do I access the iframe and override the elements style "td.rank" ? This is what I've got so far:

<script>

var head = $("#iframe11").contents().find("head");
var css = '<style type="text/css">' +
          'td.rank{background-color: #fc6b0a!important;}; ' +
          '</style>';
$(head).append(css);


</script>

<iframe src="http://www.example.com" id="iframe11" style="margin-left: 174px; width: 401px; border: 0px solid black; height: 358px; opacity: 0.85; margin-top: 23px;"></iframe>

When I open the code using "inspect element" - I don't even see the CSS code part in the <head> tag of the iframe.

Upvotes: 2

Views: 12991

Answers (2)

PCMShaper
PCMShaper

Reputation: 64

You if would like add css style inside iframe using jQuery then just follow below steps...

1. First create 'index.html' file and add below code in it

<!DOCTYPE html>
<html>
    <head>
        <script src="http://code.jquery.com/jquery-1.6.3.min.js"></script>
        <script>
        $(document).ready(function() {
            $('#iframe').load(function() {
                $("#iframe").contents().find("head").append("<style>.text_color{color:red;}@page{margin:0;}</style>");  
            });
        });
        </script>
    </head>
    <body>
        <iframe src="iframe.html" id="iframe" name="iframe"></iframe>
    </body>
</html>

2. Next create another file called 'iframe.html' and add below code to it

<!DOCTYPE html>
<html>
    <body>
        <div id="text"><span class="text_color">Content inside iframe goes here<span></div>
    </body>
</html>

3. Next run 'index.html' file and now see 'Content inside iframe goes here' text color will changed to red color

Upvotes: 3

Quentin
Quentin

Reputation: 944320

  1. Ensure that the frame document is on the same origin as the framing document so you don't have a security policy violation.
  2. Move the script so it appears after the frame so that the element exists before you try to access it
  3. Move the code into a function and use that as a load handler for the frame so that the DOM you want to manipulate exists before you try to manipulate it

Upvotes: 0

Related Questions