jQuery - Finding the element index relative to its container

Posted by Hary on Stack Overflow See other posts from Stack Overflow or by Hary
Published on 2010-04-12T01:26:57Z Indexed on 2010/04/12 1:33 UTC
Read the original article Hit count: 290

Filed under:
|

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

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about indexing