starbucks
starbucks

Reputation: 3016

Using JQuery how can I color every other row black?

I don't have a table or ul structure for this but I am using divs to display data. I need the background color of every other row to be black. I looked around but most options are for tables or list menus so a bit puzzled as to how to do this. Any idea?

My structure:

<div class="container">
     <div class="dataset">
         Thomas Jones
     </div>
     <div class="dataset">
         Edward Jones
     </div>
 <div class="dataset">
         Tommy Lee
     </div>
 <div class="dataset">
         Jenna Haze
     </div>
</div>

Upvotes: 0

Views: 523

Answers (4)

bipen
bipen

Reputation: 36531

i would go with CSS but in case you need it in jquery..then you can use :even or :odd selector.

try this

 $('div:even').css('background-color','black'); // or just background , selects all even divs.
 $('div:odd').css('background-color','black'); //selects all odd divs.

for just those divs having class dataset..add class selector to div. try this

 $('div.dataset:even').css('background','black');

Upvotes: 5

Solomon Closson
Solomon Closson

Reputation: 6217

If you must use jQuery for this:

$(".dataset").each(function(index){
    if(index%2 == 0)
       $(this).css('background', 'black');
});

jsFiddle

or use $("div.dataset:even").css('background', 'black');

jsFiddle

Upvotes: 2

Sheeban Singaram
Sheeban Singaram

Reputation: 357

Use even/odd css3 selector

HTML

<div>row1</div>
<div>row2</div>

CSS

div {
    width: 100px;
    height: 20px;
    border: 1px solid #ccc;
    color: #fff;
}

div:nth-child(odd) {
    background:red; 
}

div:nth-child(even) {
    background:black; 
}

http://jsfiddle.net/sheeban/vHGzw/

Upvotes: 2

j08691
j08691

Reputation: 207891

You can do with with just CSS(3) using :nth-child(odd) (or even):

div.dataset:nth-child(odd) {
    background: black;
}

jsFiddle example

Upvotes: 9

Related Questions