Home > Net >  How to get a index of class onhover?
How to get a index of class onhover?

Time:04-29

I have the following div structure:

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

CodePudding user response:

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

CodePudding user response:

You can try this with jQuery:

$('.test').mouseenter(function() {
  console.log("index: "   $(this).index('.test'))
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >Hover me</div>
<div >Hover me</div>
<div >Hover me</div>
<div >Hover me</div>

CodePudding user response:

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 >
  <div >Test 1</div>
</div>
<div >
  <div >Test 2</div>
</div>
<div >
  <div >Test 3</div>
</div>
<div >
  <div >Test 4</div>
</div>

CodePudding user response:

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 >Hover me 1</div>
<div >Hover me 2</div>
<div >Hover me 3</div>
<div >Hover me 4</div>

  • Related