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 a class of "current", across all sections. In this example the index of that would be 5, since it's the 5th section tag and contains a class of current.
How do I get this with jQuery?
I've started with this to get a list of all sections in the dom开发者_高级运维:
var sections = $('section');
I've tried things like this to try and get the result I want:
alert($(sections+'.current').index());
That returns a js error.
What am I missing here? Thanks!
In your code $('section')
would return you all the sections as a jquery object. Amongst them to get the index of a section which has a class of current
you could do this:
sections.index($(".current"));
This would return you a relative index of the section with class current, which would be 4 as
$('sections')
would return you a jQuery object Array(0 indexed) which contains all the sections elements. So the element which matches is the 5th element and index would return 4.
Hope this fiddle helps.
$('.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 original element relative to the elements matched by the selector. If the element is not found, .index() will return -1.
change like this
var sections = 'section';
your code is doing this and its wrong
alert($($('section')+'.current').index());
精彩评论