inspiredlife inspiredlife - 1 year ago 69
jQuery Question

How to alternate background colour on DIV rows? (Jquery and/or CSS)

I am customising the CSS for existing HTML output. So I can't change the output, I can only add script (Jquery / Javascript) and custom CSS.

The output produces rows, which form a list of items.
This is the structure of the CSS identifiers:

<div class="D F">
<div id=":b" class="G">
<div id=":c" class="G">
<div id=":d" class="G">
<div id=":e" class="G">
<div id=":f" class="G">
<div id=":g" class="G">
<div id=":h" class="G">

The ID of the divs can vary. In some cases it's as shown in my example, in other cases it has
, etc. Or some other number/letter combination. So that's not something I can rely on for making CSS declarations.

I have tried using the following script, to no effect (found, and modified from here):

$('.D>div:odd').css("background-color", "#ff0000");
$('.D>div:even').css("background-color", "#00ff00");

I also tried the following CSS (found and modified from here):

div.G div:nth-child(even) {background: #CCC;}
div.G div:nth-child(odd) { background: #FFF;}`

But this made every div row grey. They did not alternate.

I created a fiddle here:

That one includes various other divs that are nested within the divs I am targeting. I have left them in that fiddle, because for some reason (which is not clear to me) the alternate colour I declared actually affects one of the div rows (div.V). But not the others.

Here is another fiddle, with all the nested divs taken out. In this instance the same CSS has no effect at all.

Answer Source

If I understood correctly what you want,then you want to target your div's not divs inside them :

div.G:nth-child(even) {background: #CCC;}
div.G:nth-child(odd) { background: #FFF;}

It's always preferable to use css over js, because it's hardware accelarated.


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download