Ben Davidow
Ben Davidow

Reputation: 1215

Get N index of child using jQuery, with specific class

On a click event, I want to get the index of the selected element. However I don’t simply want to get N index where N means that it’s the Nth child of the parent element.

Rather I want N index where N means that it’s the Nth child of the parent element that contains a specified class. In this example, the specified index is "type-2", so the last child should have N = 2 as it’s the 3rd child of the parent element that has that class.

<div class="parent-element">
   <div class="child type-1"></div>
   <div class="child type-1"></div>
   <div class="child type-2"></div>
   <div class="child type-2"></div> 
   <div class="child type-2"></div> <!-- index should equal 2 -->
</div>

It will be selected in this manner...

$(‘.child’).click(function(){
    $(this). …
}

Upvotes: 1

Views: 255

Answers (2)

Happyriri
Happyriri

Reputation: 4443

With the @Barmar solution:

$(".child").on( 'click', function() {
  var lastClass = $(this).attr('class').split(' ').pop();
  var index = $(this).parent().children("." + lastClass).index(this);
  $("#index-clicked").html(index);
});
.child{
display: inline-block;
  width: 100px;
  height: 100px;
}

.type-1{
  background-color: gray;
}

.type-2{
  background-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="parent-element">
   <div class="child type-1"></div>
   <div class="child type-1"></div>
   <div class="child type-2"></div>
   <div class="child type-2"></div> 
   <div class="child type-2"></div>
</div>

Index clicked : <span id="index-clicked"></span>

Upvotes: 1

Barmar
Barmar

Reputation: 780673

The .index() method can be called on a collection, and it will return the index of the element within the collection. So you can use:

var index = $(this).parent().children(".type-2").index(this);

Upvotes: 4

Related Questions