Amanda Sky
Amanda Sky

Reputation: 161

Jquery selector from list

If my page has a bunch of divs like below. How can I target the individual titles with JQuery. I want to change the color on each title based on it's pos

<div id="box_list">
     <div class="container">
        <div class="title">Red</div>
        </div>
        <div class="container">
        <div class="title">Blue</div>
        </div>
        <div class="container">
        <div class="title">Orange</div>
        </div>
</div>


$(document).ready(function () {


    $("#box_list:nth-child(1)")
        .css("color", "red")


});

Upvotes: 0

Views: 49

Answers (2)

Chris Herbert
Chris Herbert

Reputation: 6285

You could use the eq() function, like this:

$("#box_list div").eq(0).css("color", "red");

Just remember that you start counting at 0 - that means you'd use .eq(2) to target the third div.

See it in action here: http://jsfiddle.net/qUYPK/

Upvotes: 1

Sushanth --
Sushanth --

Reputation: 55740

$(document).ready(function () {
    $("#box_list .title").each(function(i){
         var color = 'brown';
         if(i === 0){
             color ="red";
         }
         else if(i === 2){
             color ="orange";
         }
         $(this).css("color", color)
    });
});

Check Fiddle

Upvotes: 2

Related Questions