1

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

0

1 Answer 1

3

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>

Sign up to request clarification or add additional context in comments.

4 Comments

also $('.gallery >.select-gallery-item').click(function () { console.log($(this).index('.select-gallery-item')); }); will work?
@Supercool. It will not work if the elements are dynamic, as suggested by the usage of a delegate event handler.
When we click, it console 0, 1 , 2 why? Could you please explain. I suppose we need to show index of the element that has class select-gallery-item
@Charu It logs 0, 1, 2 because the index is based off of the result stack of the previous lookup, which contains only the elements with the desired class.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.