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!
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.