Search code examples
javascripthtmlmouseevent

Find exact Position in NodeList on MouseEvent


Seems obvious but can't find a solution.I have a couple of Div's with the same class and when you hover over them I want to know which one you exactly hovered, as a NodeList Position Value.

HTML

<div id="summary">

    <div class="articles"></div>
    <div class="articles"></div>
    <div class="articles"></div>
    <div class="articles"></div>
    <div class="articles"></div>
    <div class="articles"></div>
    <div class="articles"></div>

</div>

JS

let articles = document.querySelectorAll(".articles");

    for (let x of articles) {

        x.addEventListener('mouseenter', (e) => {

            p = Exact Position in Nodelist??
    
            console.log(articles[p]);

        });
    }

Thank you.


Solution

  • You should take the parent node's children and find its index like below.

    Try this

    let articles = document.querySelectorAll(".articles");
    
    for (let x of articles) {
      x.addEventListener("mouseenter", (e) => {
        console.log([...e.target.parentNode.children].indexOf(e.target));
      });
    }
    

    Code sandbox => https://codesandbox.io/s/young-frost-x6u1x?file=/src/index.js