0

For efficiency I'm tracking the click event against my nav rather than each li. However, each li has a set of span tags inside them. I need to manipulate the clicked li and get it's position (index). However, my e.target is showing my span tag rather than the li. I understand why but I'm not sure who to prevent it. My html is:

<nav id="nav">
  <ul>
    <li><span class="num">1</span><span class="text">Contact</span></li>
    ...
  </ul>
</nav>

and my js is basically:

  const nav = document.getElementById('nav');
  nav.addEventListener('click',navClick,false);
  function navClick(e) {
    console.log(e);
    e.stopPropagation();
  }

I know I can use closest('li') to see if I'm in the li but that doesn't seem to be giving me what I want when I need to grab the li index, add/remove classes, etc.

dcp3450
  • 10,959
  • 23
  • 58
  • 110
  • See my answer here, this might hep: https://stackoverflow.com/a/48683414/448144 The path stores the actual HTML element reference, so you should be able to extract the index or anything else from the parent `li` or use jQuery but without knowing what you mean exactly by `but that doesn't seem to be giving me what I want` it's hard to pinpoint which solution might fit best. – Nope Feb 12 '18 at 17:11
  • do you want to use jquery? – Dipak Feb 12 '18 at 17:12
  • @Dipakchavda trying to keep this pure JS. I can do this with jQuery in my sleep, lol – dcp3450 Feb 12 '18 at 17:15
  • @Nope I'll need to get the index but logging `e.target.closest('li')` returns `
  • ` which I don't think I can really use to extract location. – dcp3450 Feb 12 '18 at 17:17
  • Why not add a data-index attribute to the LI elements? – Ele Feb 12 '18 at 17:21
  • @dcp3450 `e.target.closest('li').previousSibling` Sounds like looping through the previous siblings might work ► https://stackoverflow.com/questions/5913927/get-child-node-index - Though extend that answer with a node type check as `previousSibling` also `refers to a whitespace text node rather than the actual element the author intended to get.` – Nope Feb 12 '18 at 17:26