Home > Enterprise >  Index elements with a certain class and ignore all other siblings
Index elements with a certain class and ignore all other siblings

Time:06-30

<div >
    <div ></div>
    <div ></div>
    <div ></div>
    <div ></div>
    <div ></div>
    <div ></div>
    <div ></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.

CodePudding user response:

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 >
    <div ></div>
    <div ></div>
    <div ></div>
    <div ></div>
    <div ></div>
    <div ></div>
    <div ></div>
</div>

  • Related