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?
With Hexadecimal values, you can set a background color for a div or any other element with a total of 6 characters. Hex colors start with the hash sign (#), any number from 0 to 9, and finally any letter from A to F.
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";
}
the jquery way:
$('.post:even').css('background-color','green');
$('.post:odd').css('background-color','red');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With