简体   繁体   中英

how to get the index of an element in the selection array?

I need to get the index of multiple elements regarding to their parent ol. In the code bellow I think it should give me the same index for comments and tags as they are in the same <ol> but it doesn't happen.

 $('#main-form').find('form').each(function () { //foreach form in the ol tag var $drop_target_index = $('.drop_targets').index($(this).closest('.drop_targets')); console.log($(this).closest('.drop_targets')); console.log( $drop_target_index); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="main-form"> <ol class="drop_targets"> <li><ol class="drop_targets comments"> <li><form></form> Item 1 </li> </ol> <ol class="drop_targets tags"> <li><form></form> Item 2</li> </ol></li> </ol> </div> 

I expected 0 0 I got 0 1

Use each() with your .drop_targets .

 $('.drop_targets .drop_targets').each(function () { var $drop_target_index = $(this).parent().index() + 1; console.log($drop_target_index); }) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="main-form"> <ol class="drop_targets"> <ol class="drop_targets comments"> <form></form> <form></form> <form></form> Item 1 </ol> <ol class="drop_targets tags"> <form></form> <form></form> <form></form> Item 2 </ol> </ol> </div> 

Cause you use the same class name, here is sample to change second <ol> class to get index.

<div id="main-form">
<ol class="drop_targets">
    <ol class="drop_targets1 comments">
        <form></form>
        <form></form>
        <form></form>

        Item 1
    </ol>
    <ol class="drop_targets1 tags">
        <form></form>
        <form></form>
        <form></form>
        Item 2
    </ol>
</ol>

$('#main-form').find('form').each(function (i,e) { 
console.log($('.drop_targets1').index($(e).closest('.drop_targets1')));
});

another solution don't need to edit class name

    $('#main-form').find('form').each(function (i,e) { 
        console.log($($('.drop_targets')[0]).find('.drop_targets').index($(e).closest('.drop_targets')));
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM