Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery set child CSS attribute problem

Tags:

jquery

css

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.

like image 510
Howard Zoopaloopa Avatar asked Jun 07 '26 06:06

Howard Zoopaloopa


2 Answers

Why not just:

$('#bob .divTitle').css('background-color', '#0f0');
like image 191
Keltex Avatar answered Jun 09 '26 00:06

Keltex


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>
...
like image 39
BalusC Avatar answered Jun 08 '26 23:06

BalusC