0

When traversing DOM with jQuery, is there an easy way to know how many siblings have a particular class before my selector ?

For example with the following HTML :

<ul>
    <li class="foo">One</li>
    <li>Two</li>
    <li>Three</li>
    <li>Four</li>
    <li class="foo">Five</li>
    <li>Six</li>
    <li class="active">Seven</li>
    <li>Eight</li>  
    <li class="foo">Eight</li>  
</ul>

from li.active i would like to know that i have 2 li (One and Five) with the 'foo' class preceding my active object.

Can i do that without parsing all the siblings and comparing indexes ?

I thought .prevAll() could help me but it wouldn't find more than the first sibling encountered..

skiplecariboo
  • 842
  • 2
  • 9
  • 21

2 Answers2

0

.prevAll(".foo") should be all that you need.

$(".active").prevAll(".foo");

Code example on jsfiddle.

Mark Coleman
  • 40,542
  • 9
  • 81
  • 101
0
$('.active').prevAll('.foo').length

This will return the length of a set of all previous siblings having a class of foo

js1568
  • 7,012
  • 2
  • 27
  • 47
  • Thanks, i thought prevAll was the same as prevUntil except including the matching selector.. I should pay more attention to what i read! – skiplecariboo Mar 24 '11 at 14:53