开发者

jQuery set child CSS attribute problem

I have a child element of a div named "bob" that's class is 开发者_运维技巧'.divTitle'

<div id="bob">
   <div class="divTitle">
      <a href="#">
         <h1>Title</h1>
      </a>
   </div>
</div>

I am trying to set the background color of "divTitle" to red but for the life of me can't get this to work. Right now I am trying two things...

$('#bob').children('.divTitle')[0].css('background-color', '#0f0'); // assuming children is returning an array...

and

$('#bob').children('.divTitle').css('background-color', '#0f0');

neither with any success... can anyone tell me what I am missing here? Do I have to go deeper than ".children"?

EDIT

Unfortunately, I guess the important part of this question was omitted. I was generating this div dynamically, and making reference to the class was just coming up empty. So, instead of referencing the dynamically generated interior div by class type, I gave it a unique id and now can manipulate it as I wish... I'm still giving the check mark to Keltex for pointing out a better direct reference method.


Why not just:

$('#bob .divTitle').css('background-color', '#0f0');


The second should work fine. Your problem lies somewhere else.

First thing: are you executing this code when the document is ready loading/populating the elements of interest?

<head>
    ...
    <script>
        $(document).ready(function() {
            $('#bob .divTitle').css('background-color', '#0f0');
        });
    </script>
</head>
...

If not, then do so, or move the script to after the DOM elements of interest.

...
<div id="bob">
   <div class="divTitle">
      <a href="#">
         <h1>Title</h1>
      </a>
   </div>
</div>
<script>
    $('#bob .divTitle').css('background-color', '#0f0');
</script>
...


$('#bob').children('.divTitle')[0] <-- this is returning the dom object rather than the jQuery object which is why this one doesn't work.

The second one should work for you though, I've done what you have above as an example.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜