简体   繁体   中英

Get position of first occurrence of class (Jquery)

How can I detect the position of a section, which is the first section with a specific class?

For instance I have four sections:

  • The first section has the class banana
  • the second section class apple
  • the third also apple
  • the last orange .

How can I detect the position of the first occurrence of apple — which would be position 2?

You can use the index() method to achieve this, if you provide it a selector to group by. Try this:

 var appleIndex = $('.apple').index('.section'); console.log(appleIndex); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="section banana">Banana</div> <div class="section apple">Apple</div> <div class="section melon">Melon</div> <div class="section grape">Grape</div> 

Note that the index is zero-based, so the second item would be index 1 , not 2 as in your question. You can easily add 1 to it if require, though.

You can write a jQuery plugin to iterate over the elements and retrieve their position.

The following function is a jQuery plugin to iterate over some elements and check if it has a particular class. If it has it, its position will be returned.

(function($) {
  $.fn.idiciesOfClass = function(className) {
    return this.map(function(index) {
      return $(this).hasClass(className) ? index : -1;
    }).toArray().filter(function(pos) {
      return pos > -1;
    });
  }
})(jQuery);

Demo

 (function($) { $.fn.idiciesOfClass = function(c) { return this.map((i, e) => $(e).hasClass(c) ? i : -1).toArray().filter(x => x > -1); } })(jQuery); console.log('Apple class indicies:', $('.section').idiciesOfClass('apple').join(', ')); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="section banana">Banana</div> <div class="section apple">Apple</div> <div class="section apple">Apple</div> <div class="section orange">Orange</div> 

Apple class indicies: 1, 2

If they are all located within a id='parent' object, then you can do it like so:

$('#parent').children().each(function (i, v) {
    if ($(v).hasClass("apple"))
    {
        console.log(i);
        return false;
    }
});

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