Reputation:
I need to find and style the class before only the :last
selector (real second-last),
and the class after only the :first
selector (real second).
I've tried with nth-child()
and nth-last-child()
,
but they dont select only the very second-last and only the very second classes over the entire page..
$('.myClass:first ').addClass("myClassStart");
$('.myClass:nth-child(2) ').addClass("myClassStart2");
$('.myClass:nth-last-child(2) ').addClass("myClassEnd2");
$('.myClass:last ').addClass("myClassEnd");
NOTE: only the :first
, and the :last
selectors actually work well
Upvotes: 1
Views: 44
Reputation: 262939
An easy way to achieve this is to use the :eq() selector:
$(".myClass:eq(1)").addClass("myClassStart2");
$(".myClass:eq(-2)").addClass("myClassEnd2");
:eq()
is zero-based, passing it 1
matches the second element in the set. When fed a negative number, :eq()
matches backwards from the end of the set, starting at -1
, so -2
matches the next-to-last element.
You will find an updated fiddle here.
Upvotes: 1