1
<div class="collection">
    <div class="item"></div>
    <div class="item selected"></div>
    <div class="item"></div>
    <div class="item selected"></div>
    <div class="item"></div>
    <div class="item selected"></div>
    <div class="item"></div>
</div>

How would I get the index of the divs with class "selected" to ignore the other siblings? in this case it should return 0 1 2, and not 1 3 5.

biberman
  • 5,606
  • 4
  • 11
  • 35
DNa
  • 67
  • 4
  • 2
    Index relative to what? The index of the divs with class "selected" relative to the "collection"-div are exactly 1, 3 and 5. Also what are you trying to achieve? – Esko Jun 29 '22 at 11:20
  • 3
    Pass a selector to `index()` which is the set you want to find the index of the current element within. eg: `$(this).index('.selected')` – Rory McCrossan Jun 29 '22 at 11:24
  • _"in this case it should return 0 1 2"_ - what is "it"? What exactly are you trying to call, and in what context? Maybe you should just use `$('.item.selected').length` to figure out that there _are_ three of those items ... and if you really _need_ an array containing the numbers 0, 1 and 2 based on that, create it: https://stackoverflow.com/a/33352604/1427878 – CBroe Jun 29 '22 at 14:20
  • Thanks guys. I'm basically using this function to hide/show divs and assign a class on the shown divs to limit them, but because there would be other divs with indexation I'm trying to index only the selected ones to hide them above a specific number for a "load more" button. Rory's idea worked perfectly! – DNa Jun 29 '22 at 16:30

1 Answers1

0

Like Rory McCrossan wrote, use a selector for the index() method:

index('.selected')

Working example:

$('.selected').each(function() {
  console.log($(this).index('.selected'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="collection">
    <div class="item"></div>
    <div class="item selected"></div>
    <div class="item"></div>
    <div class="item selected"></div>
    <div class="item"></div>
    <div class="item selected"></div>
    <div class="item"></div>
</div>
biberman
  • 5,606
  • 4
  • 11
  • 35