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 whatindex
gives you if you call it on the element without arguments. So in youreach
:...gives you the index of the selected element.
Live Example:
You could even get an array of those indexes by using
map
, returning the index out of the callback, and usingget
to turn the jQuery result into a true array:Live Example: