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
source share
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
source

You can use prevAll jquery method ,

if currentelem is a reference to your element, then

 $(currentelem).prevAll().length 

Gives you the number of elements in front of your element inside the same parent or container.

+3
source

If you have a target element:

$(this).prev(".create-q").length and $(this).next(".create-q").length

0
source

you can use loop through selected elements using jQuery

Link Example

jquery link

jsfiddle demo

 <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
source

Source: https://habr.com/ru/post/917091/


All Articles