Sean
Sean

Reputation: 344

jQuery :odd or :even to addClass up to a certain selector?

I need to add an alt class (on odd or even) to a selector, and then start fresh again after it reaches another selector.

What I have

<div class="person"></div>
<div class="person"></div>
<div class="person"></div>
<div class="person"></div>
<div class="person"></div>
<div class="section-separator"></div>
<div class="person"></div>
<div class="person"></div>

What I need

<div class="person"></div>
<div class="person alt"></div>
<div class="person"></div>
<div class="person alt"></div>
<div class="person"></div>
<div class="section-separator"></div>
<div class="person"></div>
<div class="person alt"></div>

The issue I run into is it wants to keep counting odd/even from the previous section and not start over again, so my styles do no apply correctly. My current jQuery is $('.personbox:odd').addClass('alt');

Upvotes: 2

Views: 48

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074694

I don't think there's a clever way to do this. The un-clever way is just select the .person and .section-separator elements and loop through, keeping track of an index:

var index = 0;
$(".person, .section-separator").each(function() {
  var $this = $(this);
  if ($this.hasClass("section-separator")) {
    index = 0;
  } else {
    if (index % 2 == 1) {
      $this.addClass("alt");
    }
    ++index;
  }
});
.alt {
  color: blue;
}
<div class="person">testing</div>
<div class="person">testing</div>
<div class="person">testing</div>
<div class="person">testing</div>
<div class="person">testing</div>
<div class="section-separator">separator</div>
<div class="person">testing</div>
<div class="person">testing</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Upvotes: 3

Related Questions