Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
713 views
in Technique[技术] by (71.8m points)

jquery - Getting the index of a current element across 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 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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...