Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count elements before an element

Tags:

jquery

here is an example :

<div class="create-q"></div>
<div class="create-q"></div>
<div class="create-q"></div>
<div class="create-q"></div> <-- im in this class : I want to know how many div with class "create-q" there is before this one. (3 in this example)
<div class="create-q"></div>
<div class="create-q"></div>

I know how to count but not how to stop it once it reach a specified div..

How can I do this with jQuery ?

like image 243
user1428252 Avatar asked May 31 '12 11:05

user1428252


2 Answers

If mydiv is a reference to the element you're already looking at:

var n = $(mydiv).index('.create-q');

will give the index of that div which as they're zero-based also happens to be the number of preceding divs.

Unlike .prevAll() this will work regardless of whether the divs have a common parent or not.

like image 173
Alnitak Avatar answered Sep 28 '22 04:09

Alnitak


You can use jquery's prevAll method,

if currentelem is the reference to your element then,

$(currentelem).prevAll().length 

Would give you the number of elements before your element within the same parent or container.

like image 34
Ashwin Krishnamurthy Avatar answered Sep 28 '22 03:09

Ashwin Krishnamurthy