Jonathan
Jonathan

Reputation: 31

Applying CSS through jQuery to a div called by Javascript?

I have the following:

<div>
<script type="text/javascript" src="someUrl"></script>
</div>

That script generates a div with some links inside of it so it's like:

<div>
    <div>
    <a href=""></a>
    </div>
</div>

I need to style those links to be a certain color with jQuery because that's the way the page was developed.

Right now I have the following:

<script type="text/javascript">
    $(document).ready(function () {
         $("div a").css("color","#ffffff");
    });
</script> 

The only browser that changes the links to white is Firefox because, I believe, FF loads pages differently and is applying these styles after the script creates the div? How do I make this work across all browsers?

Upvotes: 3

Views: 141

Answers (2)

DMin
DMin

Reputation: 10353

Code below works, I guess this is what you want.

<script type="text/javascript">
    $(document).ready(function() {

    $("#click").click(function(){
     $("#maindiv").append("<div><div><a href='example.com'>AAA</a></div></div>");
     $("#maindiv > div a").css("color","#ffffff");      
       });    
    });
</script>    


<div id="maindiv">
<div>
    <div>
    <a href=""></a>
    </div>
</div>
</div>

<a id="click" href="#">Click Here</a>

After your JS generates the div, you should then set the CSS, it will work.

Upvotes: 1

alex
alex

Reputation: 490263

So, assuming for some strange reason you are unable to use an external stylesheet, you could always add them inline, with your script, by adding style="color: blue;".

Or failing that, make sure your selector is selecting what you really want. Can you put an id on that wrapping div, and then use a selector like $('#my-div > div a') (assuming you only want to add colour to the direct descendants).

Upvotes: 0

Related Questions