Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85653

select coressponding next child element

I have the following html

<div id="test">
<p class="one"></p> <---first one----->
<p class="two"></p>
<p class="three"></p>
<p class="four"></p>
<p class="one"></p> <---second one---->
<p class="two"></p>
<p class="three"></p>
<p class="four"></p>
<p class="one"></p> <--- third one----->
<p class="two"></p>
<p class="three"></p>
<p class="four"></p>
</div>

Ok, now I'm at first .one class then I would like to select next .one class and again if I'm in second one then I would like to select next .one class from this. I think there is not :next-child something like this .one:next-child so how could I do?


update

@chopper answer is okay! but if it cannot find next one then it should select first one

Upvotes: 0

Views: 233

Answers (2)

chopper
chopper

Reputation: 6709

Use the jQuery .next() selector:

var secondOne = firstOne.next('.one');

EDIT: @KevinB is right, the correct answer is

var secondOne = firstOne.nextAll('.one:first');

or

var secondOne = firstOne.nextAll('.one').first();

Upvotes: 3

Mr_Green
Mr_Green

Reputation: 41872

I am not sure what you are trying. if you want the next .one you can just use the sibling selector.

p.one ~ p.one ~ p.one{
    background-color: green;
}

Working fiddle

For example, if you want the second .one then do like this:

p.one ~ p.one {
     /* apply styles */   /* selects all sibling elements */
}

p.one ~ p.one ~ p.one{           /* overriding css  styles */
     /* apply default styles */  /* selects all other sibling elements leaving the second element */ 
}

Working fiddle (on hover)

Upvotes: 1

Related Questions