My simplified scenario:
<div id="container-1" class="container">
<div class="content">
<div class="item selected"></div>
<div class="item"></div>
<div class="item"></div>
</div>
</div>
<div id="container-2" class="container">
<div class="content">
<div class="item"></div>
<div class="item selected"></div>
<div class="item"></div>
</div>
</div>
I need to find index of class="selected" within class="content" for each class="container", so the expected results for the above scenario would be:
0, 1
I'm trying to achieve this with jQuerys 'each' function like so:
$('.container').each(function()
{
$(this).find('.item').index('.selected');
$('#' + $(this).attr('id') + ' .item').index('.selected');
$(this).find('.selected').index();
});
But I'm getting only -1 results.
Sounds like you want the index of the .selected
amongst its siblings, which is what index
gives you if you call it on the element without arguments. So in your each
:
$(this).find(".content .selected").index()
...gives you the index of the selected element.
Live Example:
$(".container").each(function() {
console.log($(this).find(".content .selected").index());
});
<div id="container-1" class="container">
<div class="content">
<div class="item selected"></div>
<div class="item"></div>
<div class="item"></div>
</div>
</div>
<div id="container-2" class="container">
<div class="content">
<div class="item"></div>
<div class="item selected"></div>
<div class="item"></div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You could even get an array of those indexes by using map
, returning the index out of the callback, and using get
to turn the jQuery result into a true array:
var indexes = $(".container").map(function() {
return $(this).find(".content .selected").index();
}).get();
Live Example:
var indexes = $(".container").map(function() {
return $(this).find(".content .selected").index();
}).get();
console.log(indexes);
<div id="container-1" class="container">
<div class="content">
<div class="item selected"></div>
<div class="item"></div>
<div class="item"></div>
</div>
</div>
<div id="container-2" class="container">
<div class="content">
<div class="item"></div>
<div class="item selected"></div>
<div class="item"></div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>