How to get an index of an element of a specific class

I need to get an index of the item I clicked, but only an index of items with a specific class.

<div class="gallery">

   <div class="gallery-item"></div>
   <div class="gallery-item"></div>
   <div class="gallery-item select-gallery-item"></div> <!-- click on this -->
   <div class="gallery-item"></div>
   <div class="gallery-item"></div>
   <div class="gallery-item select-gallery-item"></div>
   <div class="gallery-item select-gallery-item"></div>
   <div class="gallery-item select-gallery-item"></div>

</div>
$('.gallery').on('click', '.select-gallery-item', function () {
   $(this).index();
};

For example, I click on this element with a class '.select-gallery-item', I will get an index - 2. But among the elements with the class '.select-gallery-item', its index - 0

Upvotes: 1

Views: 148

Answers (1)

Taplar
Taplar

Reputation: 24965

Call index(this) off of the selected elements the index should be based upon.

$('.gallery').on('click', '.select-gallery-item', function () {
   console.log($('.select-gallery-item').index(this));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="gallery">

   <div class="gallery-item">a</div>
   <div class="gallery-item">b</div>
   <div class="gallery-item select-gallery-item">c</div> <!-- click on this -->
   <div class="gallery-item">d</div>
   <div class="gallery-item">e</div>
   <div class="gallery-item select-gallery-item">f</div>
   <div class="gallery-item select-gallery-item">g</div>
   <div class="gallery-item select-gallery-item">h</div>

</div>

Upvotes: 3

Related Questions