简体   繁体   中英

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/

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM