Count items before item
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 reaches the specified div.
How can I do this using jQuery?
+6
4 answers
If mydiv
is a link to an element that you are already viewing:
var n = $(mydiv).index('.create-q');
will give an index to this div, which, since they are based on zero, is also the number of previous divs.
Unlike .prevAll()
, this will work regardless of whether the div has one common parent or not.
+23
you can use loop through selected elements using jQuery
<div id="example"> <div class="create-q">1</div> <div class="create-q">2</div> <div class="create-q">3</div> <div class="create-q">thisOne</div> <div class="create-q">5</div> <div class="create-q">6</div> </div>
function example(thisOne) { var count=0; var hrefs = ''; $('#example div').each(function(idx, item) { //alert(item); return object HTMLDivElement hrefs += item.innerHTML+ '\n' ; count+=1; if(item.innerHTML==thisOne) { //this is what you want the nubmber of elements before thisOne alert(count-1); return 0; } }); window.alert(hrefs); }
-1