How to get index number of clicked element from MouseEvent object

Viewed 1690

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/

2 Answers

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>

There are a few ways to go about this depending on how you want to use the index of each child element. I think using data attributes is generally a good approach:

HTML

<div id="container">
  <div data-id="1">1z</div>
  <div data-id="2">2z</div>
  <div data-id="3">3z</div>
  <div data-id="4">4z</div>
  <div data-id="5">5z</div>
  <div data-id="6">6z</div>
</div>

JS

const container = document.getElementById("container");

function handleClick(evt) {
  const childNode = evt.target.closest("div");
  console.log(childNode.dataset.id);
}

container.addEventListener("click", handleClick, false);
Related