Getting the index of the current element in all matched elements in the DOM

I have a DOM structure that looks like this:

<div class="chapter"> <section></section> <section></section> </div> <div class="chapter"> <section></section> <section></section> <section class="current"></section> <section></section> </div> <div class="chapter"> <section></section> <section></section> <section></section> <section></section> </div> 

I want to get the index number of the section with the class "current" for all sections. In this example, the index of this will be 5, since this is the tag of the 5th section and contains the class of the current one.

How do I get this using jQuery?

I started with this to get a list of all sections in dom:

 var sections = $('section'); 

I tried things like this to try and get the result I want:

 alert($(sections+'.current').index()); 

This returns a js error.

What am I missing here? Thanks!

+6
source share
3 answers

In your $('section') code, all sections will be returned as a jquery object. Among them, to get the index of the section that the current class has, you could do this:

 sections.index($(".current")); 

This will return you the relative index of the section with the current class, which will be 4 as $('sections') will return you a jQuery array object (0 indexed), which contains all the elements of the sections. So the element that corresponds to the 5th element and the index will return 4. Hope this fiddle helps.

+11
source
 $('.current').index('section'); 

See the docs on index .

If a selector string is passed as an argument, .index () returns an integer indicating the position of the source element relative to the elements corresponding to the selector. If the item is not found, .index () will return -1.

+6
source

change it like

 var sections = 'section'; 

your code does this and its wrong

 alert($($('section')+'.current').index()); 
0
source

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


All Articles