Search code examples
jquerycss-selectorsjquery-traversing

How to use jQuery nth-child to color every other div in parent and rest on new parent?


Have to support IE8 so no just css.

I am trying to color the odds and evens of each parent div and reset the color when it hits the new parent div. Hope that makes sense. Here is an example:

<div class="date">
<h2>Content</h2>
(White BGColor this div)<div class="option-heading"> 
    <div class="arrow-up">&#9650;</div>
    <div class="arrow-down">&#9660;</div>
    <p>Content</p>
</div>
(ignore)<div class="option-content">
    <p>Content</p>
</div>
(Blue BGColor this div)<div class="option-heading"> 
    <div class="arrow-up">&#9650;</div>
    <div class="arrow-down">&#9660;</div>
    <p>Content</p>
</div>
(ignore)<div class="option-content">
    <p>Content</p>
</div>
(White BGColor this div)<div class="option-heading"> 
    <div class="arrow-up">&#9650;</div>
    <div class="arrow-down">&#9660;</div>
    <p>Content</p>
</div>
(ignore)<div class="option-content">
    <p>Content</p>
</div>
</div>
(reset to color first white)
<div class="date">
<h2>Content</h2>
(White BGColor this div)<div class="option-heading"> 
    <div class="arrow-up">&#9650;</div>
    <div class="arrow-down">&#9660;</div>
    <p>Content</p>
</div>
(ignore)<div class="option-content">
    <p>Content</p>
</div>
(Blue BGColor this div)<div class="option-heading"> 
    <div class="arrow-up">&#9650;</div>
    <div class="arrow-down">&#9660;</div>
    <p>Content</p>
</div>
(ignore)<div class="option-content">
    <p>Content</p>
</div>
</div>

I use this jQuery

           $ ('div.option-heading p:odd').css("background-color","#e3e8ea");
       $ ('div.option-heading p:even').css("background-color","#fff");

But it doesn't reset on the new parent div.


Solution

  • You could use a loop on the parent elements so every time the code reaches a new parent element (<div class="date"></div> in your case), it will reset the styles:

    $('div.date').each(function() {
      $(this).find('div.option-heading:odd').css('background-color', '#e3e8ea');
      $(this).find('div.option-heading:even').css('background-color','#fff');
    });