MrCroft MrCroft - 2 months ago 13
jQuery Question

jQuery - get index of element, restricted to class

Given the following html:

<div class="my-container">
<div class="x">
<a href="#">Link 1</a>
</div>
<div class="x">
<a href="#">Link 2</a>
</div>
<div class="x">
<a href="#">Link 3</a>
</div>
<div class="x y">
<a href="#">Link 4</a>
</div>
<div class="x">
<a href="#">Link 5</a>
</div>
<div class="x y">
<a href="#">Link 6</a>
</div>
<div class="x">
<a href="#">Link 7</a>
</div>
</div>


Which elements get the
y
class - is a dynamic thing, which changes during runtime based on different user interactions.

On mouse over an anchor (I can assume that the anchor is in a div with the
y
class, because only those are visible), I need to get the index of it's container (that div with the
y
class), but restricted to that
y
class.

Meaning:


  1. mouseover on "Link 4" should tell me:
    0
    (first element with class
    y
    )

  2. mouseover on "Link 6" should tell me:
    1
    (second element with class
    y
    )



.index()
doesn't help me here

EDIT:
@Kevin B
I've read the docs, but couldn't make it work. The closest thing I could find there was to pass a collection to
.index()
, which I've tried. But didn't work (also, their example for the collection is with vanilla js document.getElementById - that didn't work for me, need to work with classes; tried to adapt: myCollection = $(this).closest('.my-container').children('.y') and passed that to
.index()
, and it didn't work).
I wouldn't post without google-ing first and also going through the docs, don't know why the down vote (not pointing any fingers, I'm not assuming I know who's is it). Just because I said ".index()" doesn't help me"? Well, I've tried whatever I understood I could do with it, and couldn't make it happen. That's why I posted.

Answer

As said in the comments, index is exactly what you need:

$(document).ready(function() {
  //mousein
  $("a").hover(function(){
     var parent = $('.my-container').eq(2); // the 3rd "my-container"
     console.log(parent.find('.y a').index(this)); //-1 if elm doesnt exist
  },
  //mouseout
  function(){

  })
});