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 ?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With