'How to get a index of class onhover?

I have the following div structure:

<div class="0">
     <div class="test"></div>
</div>
<div class="1">
     <div class="test"></div>
</div>
<div class="2">
     <div class="test"></div>
</div>
<div class="3">
     <div class="test"></div>
</div>

For example, if I hover on the 1st class: document.getElementbyClassName('test')[0], I should get index value is 0.

Edit: I'm looking for a pure JS solution



Solution 1:[1]

You can use the following code:

$('.test').mouseenter(function() {
  console.log("index: " + $(this).index('.test'));
})

$('.test').mouseenter(function() {
  console.log("index: " + $(this).index('.test'));
})
.test {
  height: 100px;
  width: 100px;
  border: 1px solid blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>

Solution 2:[2]

To do this in pure JS you can use querySelectorAll() to retrieve the target elements and bind a mouseenter event handler to them. Then you can find the index of the element which triggered the event by comparing it to the collection of children in the parent. Something like this:

let elements = document.querySelectorAll('.test');

elements.forEach(el => el.addEventListener('mouseenter', e => {
  let index = Array.from(elements).indexOf(e.target);
  console.log(index);
}));
<div class="1">
  <div class="test">Test 1</div>
</div>
<div class="2">
  <div class="test">Test 2</div>
</div>
<div class="3">
  <div class="test">Test 3</div>
</div>
<div class="4">
  <div class="test">Test 4</div>
</div>

Solution 3:[3]

This code Use pure java script :

    var divItems = document.querySelectorAll(".test");
    var mytab = [];
    var index = 0;
    for (let i = 0; i < divItems.length; i++) {
      mytab.push(divItems[i].innerHTML);
    }

    for (var i = 0; i < divItems.length; i++) 
    {
      divItems[i].onmouseover = function () 
      {
         index = mytab.indexOf(this.innerHTML);
         console.log(this.innerHTML + " Index = " + index);
      };
    }
<div class="test">Hover me 1</div>
<div class="test">Hover me 2</div>
<div class="test">Hover me 3</div>
<div class="test">Hover me 4</div>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Carsten Løvbo Andersen
Solution 2
Solution 3 Prakash Solanki