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

前端 未结 3 1650
滥情空心
滥情空心 2020-12-18 03:22

I have a DOM structure that looks like this:

相关标签:
3条回答
  • 2020-12-18 03:50
    $('.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.

    0 讨论(0)
  • 2020-12-18 03:52

    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.

    0 讨论(0)
  • 2020-12-18 04:00

    change like this

    var sections = 'section';
    

    your code is doing this and its wrong

    alert($($('section')+'.current').index()); 
    
    0 讨论(0)
提交回复
热议问题