JQuery - finding an index of an element relative to its container

Here is 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 (given the index based on 0), not 1.

My usual way of getting indexes is used $element.prevAll().length, but obviously this will return the index with respect to div # inner-2.

I tried using $('img.selected').prevAll('#main').lengthbut return 0: /

+3
source share
1 answer

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

$('#main img').index('img.selected');
+9
source

Source: https://habr.com/ru/post/1740715/


All Articles