Search code examples
javascriptdommouseeventqueryselector

How to get index number of clicked element from MouseEvent object


I am trying to get the index of the clicked element from the MouseEvent object. When I go console click event objects "path" property and hover to first array item it marks actually clicked element.

I wonder how come engine knows which was clicked? Because event.path[0] selector doesn't contain index number of clicked element.

<div id="container">
    <div>abc</div>
    <div>abc</div>
    <div>abc</div>
    <div>abc</div>
    <div>abc</div>
    <div>abc</div>
</div>

jsfiddle: https://jsfiddle.net/9n3f7mcr/


Solution

  • You can use Array#indexOf on the children of the parent of event.target, if all the elements you may want the index of have the same parent.

    document.addEventListener('click', function (e) {
      var target = e.target;
      var parent = target.parentNode;
      var index = [].indexOf.call(parent.children, target);
      console.log("index:", index);
    });
    <div id="container">
    <div>1z</div>
    <div>2z</div>
    <div>3z</div>
    <div>4z</div>
    <div>5z</div>
    <div>6z</div>
    </div>