Alternate div background color

redgem picture redgem · May 30, 2011 · Viewed 10.8k times · Source

I have a structure like the following:

<div class="wrapper"...>
   <a href="#"...>blah</a>
   <div class="post"...>stuff</div>
</div>

And it repeats throughout a dynamic page a few times. I would like to alternate the background colors of the div class "post" with two colors, but CSS's nth-child pseudo class only seems to work with items that are directly sequential.

Is there a way (CSS, Javascript, jQuery, etc.) that I can alternate the div background colors?

Answer

Thomas Shields picture Thomas Shields · May 30, 2011

jQuery's :odd and :even selectors are pretty handy:

$(".post:even").css("background-color","blue"); 
$(".post:odd").css("background-color","red"); 

HTML:

<div class="wrapper">
   <a href="#">blah</a>
   <div class="post">stuff</div>
</div>
<div class="wrapper">
   <a href="#">blah</a>
   <div class="post">stuff</div>
</div>
...

http://jsfiddle.net/thomas4g/uaYd9/2/

EDIT:

The non-jQuery, quick JS way:

var posts = document.getElementsByClassName("post");
for(var i=0;i<posts.length;i++) {
  posts[i].classList.add(i % 2 === 0 ? "even" : "odd");
  //or
  posts[i].style["background-color"] = i % 2 === 0 ? "blue" : "red";
}