Zerobu
Zerobu

Reputation: 2701

Alternating background color of items in an unordered list

I have an Ul of item. I want to alternate there background color here is the html

<html> 
  <head> 
    <title>JQuery Problem 1</title> 
    <script type="text/javascript" src="jquery-1.4.min.js"></script> 
    <script type="text/javascript" src="problem1.js"></script> 
  </head> 
  <body> 
    <ol> 
      <li>Comp 250
        <ul> 
          <li>HTML</li> 
          <li>CSS</li> 
          <li>CGI</li> 
          <li>PHP</li> 
          <li>JavaScript</li> 
        </ul> 
      </li> 
      <li>Comp 345
        <ul> 
          <li>Objects and classes</li> 
          <li>Static and constant members</li> 
          <li>Operator overloading</li> 
          <li>Templates</li> 
          <li>Inheritance</li> 
          <li>Polymorphism</li> 
        </ul> 
      </li> 
      <li>Comp 431
        <ul> 
          <li>Perl language</li> 
          <li>File uploads and downloads</li> 
          <li>AJAX and JSON</li> 
          <li>Java Servlets</li> 
          <li>JSP</li> 
        </ul> 
      </li> 
    </ol> 
  </body> 
</html> 

Here is ma JQuery

$(document).ready(function()
{


    $("ol > li").css({margin: "1em", fontWeight: "bold"});
    $("ol li li").css({fontWeight: "normal"}); 
    $("ul li").css('border', '1px solid white'); 

     $("ul li").hover(function()
        {
            $(this).css('border', '1px solid red'); 
        },
        function()
        {
            $(this).css('border', '1px solid white')
        });


});

Now i want to alternate, the first item in the ul should always be #FDD and the second #FFD

Upvotes: 1

Views: 1840

Answers (1)

cletus
cletus

Reputation: 625317

One line version:

$("ol > li").filter(":nth-child(odd)").css("background", "#FDD")
  .end().filter(":nth-child(even)").css("background", "#FFD");

Two line version:

$("ol > li:nth-child(odd)").css("background", "#FDD");
$("ol > li:nth-child(even)").css("background", "#FFD");

or using each():

$("ol > li").each(function(i, val) {
  $(this).css("background", i & 1 ? "#FFD" : "#FDD");
});

Upvotes: 3

Related Questions