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.

6
  • See my answer here, this might hep: 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. Commented Feb 12, 2018 at 17:11
  • do you want to use jquery? Commented Feb 12, 2018 at 17:12
  • @Dipakchavda trying to keep this pure JS. I can do this with jQuery in my sleep, lol Commented Feb 12, 2018 at 17:15
  • @Nope I'll need to get the index but logging e.target.closest('li') returns <li></li> which I don't think I can really use to extract location. Commented Feb 12, 2018 at 17:17
  • Why not add a data-index attribute to the LI elements? Commented Feb 12, 2018 at 17:21

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.