0

I have following markup:

<div class="region">
<div class="award">
<div class="award">
<div class="region">
<div class="award">
<div class="award">
<div class="award">
<div class="award">
<div class="award">
<div class="award">

How can I target the 3rd element after .region so that I get something like this?

<div class="region">
<div class="award">
<div class="award">
<div class="region">
<div class="award">
<div class="award">
<div class="award third">
<div class="award">
<div class="award">
<div class="award third">

Note that it is not counting the first two .award elements after first .region.

Thanks in advance!

itsututa
  • 157
  • 4
  • 7
  • possible duplicate of http://stackoverflow.com/questions/1260277/addclass-every-nth – Armatus Apr 19 '12 at 14:12
  • @Armatus: I don't think so, not with the varying starting points. – T.J. Crowder Apr 19 '12 at 14:19
  • These divs are meant to be *siblings*, right? You haven't closed them, which means you have eight layers of children there, but I'm sure that's not what you meant... – T.J. Crowder Apr 19 '12 at 14:21
  • 1
    @T.J.Crowder True, a slight difference I did not fully notice. Please regard my comment as a reading suggestion for ideas in that case :) – Armatus Apr 19 '12 at 14:22

1 Answers1

2

nextUntil combined with eq should do it:

$("div.region").each(function() {
    $(this).nextUntil(":not(.award)").eq(2).addClass("third");
});

Nope, a little more complicated than that, to handle the 6th element:

$("div.region").each(function() {
    $(this).nextUntil(":not(.award)").filter(function(index) {
        return index % 3 == 2;
    }).addClass("third");
});

Live example | source

There we grab each of the .region elements, get their siblings up to the first one that isn't an .award (nextUntil), and filter out ones that aren't every third one.

(Not sure why I used map in my first working copy, filter makes much more sense.)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • making the assumption that each of the div is actually not nested and are closed, (bad markup in example from OP) this would not select the 10th (last) div as a second "3rd" element. – Mark Schultheiss Apr 19 '12 at 14:19
  • Yep, i was looking at the original as it seemed to not suffice :) had to study it a bit :) Check this one off as working now. – Mark Schultheiss Apr 19 '12 at 14:24
  • @MarkSchultheiss: Yeah, I facepalmed a bit when I did the live example. And I just realized that even in the fix, I used `map` where `filter` would be the more appropriate choice, so I've fixed that too. – T.J. Crowder Apr 19 '12 at 14:26
  • Yes, that is better, but they both work. Makes me wonder which is faster :) – Mark Schultheiss Apr 19 '12 at 14:28
  • @MarkSchultheiss: Oh, wave the red flag why don't you. ;-) Looks like `filter`, which probably shouldn't surprise us: http://jsperf.com/silly-map-vs-filter – T.J. Crowder Apr 19 '12 at 15:33