views:

38

answers:

1

Here's my HTMl structure:

<div id="main">
   <div id="inner-1">
      <img />
      <img />
      <img />
   </div>

   <div id="inner-2">
      <img />
      <img class="selected" />
      <img />
   </div>

   <div id="inner-3">
      <img />
      <img />
      <img />
   </div>
</div>

What I'm trying to do is get the index of the img.selected element relative to the #main div. So in this example, the index should be 4 (assuming 0 based index) and not 1.

My usual way to go about getting indexes is using $element.prevAll().length but, obviously, that will return the index relative to the #inner-2 div.

I've tried using $('img.selected').prevAll('#main').length but that's returning 0 :/

+4  A: 

This will work; it finds the index of the selected image within the set of all img tags inside #main.

$('#main img').index('img.selected');
meagar
That works perfectly. Cheers.
Hary
FYI `index()` can take a selector so `$("#main img").index("img.selected")` is valid.
cletus
Cool! I learned s/t new
Atømix
@cletus Of course :| Updated answer, thanks for catching that.
meagar