I have a series of divs in two columns with some javascript dictating some behavior, and I’d like to have the background colors of certain div classes alternate.
Here’s the javascript that supposed to handle this:
<script type="text/javascript">
$(document).ready(function(){
$('#faqlist div.faq-title:nth-child(odd)').addClass('alternate');
});
</script>
With the stylesheet calling the alternate div background color:
div.alternate { background: #c1c1c1 }
And here’s the html:
<div id="faqlist">
<div class="faq-title"></div>
<div class="faq-answer"></div>
<div class="faq-title"></div>
<div class="faq-answer"></div>
<div class="faq-title"></div>
<div class="faq-answer"></div>
</div>
Right now, the result is every div of class “faq-title” has the #c1c1c1 background color, leading me to believe that I’m missing something simple. Like the javascript suggests, I want only the alternating “faq-title” class divs to have the #c1c1c1 background color, and the “faq-answer” divs to get ignored.
jsFiddle: http://jsfiddle.net/inerdial/mRaRW/
As you’ve discovered,
nth-childtakes its numbering from the parent element, not the results of the specific selector (see the jquery documentation).Use
:even, which does what you want:http://jsfiddle.net/uJqPg/
Note that
:evenis 0-based, whilenth-child(following the css spec) is 1-based, hence the even/odd mismatch. Also,:evenis a jquery extension, and will not be native on any browser.