1

This is my html code.

<ul class="listClass">
    <li>List1</li>
    <li>List2</li>
    <li>List3</li>
    <li>List4</li>
    <li>List5</li>
</ul>

I'm adding an onClick eventListener to the child <li>s, which should output me the correct index of that child <li>

Here's the javascript

var lists = document.querySelectorAll('.listClass li');
for (var i = 0; i < lists.length; i++) {
    lists[i].addEventListener('click', function (e) {
        console.log(e);
      console.log('My index:', i);
    }, false);
}

It always outputs:My index: 5

While I clearly understand that, it's taking the reference of i, Is there any other way I can store the correct value of i.

Two possible approaches that I found out.

1st: Jquery's index() method. https://api.jquery.com/index/

2nd: DOM event delegation. What is DOM Event delegation?

Is there any other approach that can be used? Thanks.

Community
  • 1
  • 1
nitte93user3232918
  • 1,443
  • 2
  • 17
  • 34

1 Answers1

1

You can add a property to your element

var list2 = document.querySelectorAll('.list2 li');

for (var i = 0; i < list2.length; i++) {  
  
  list2[i].index = i;
  
  list2[i].addEventListener('click', function(e) {
    
    alert('My index:' + e.target.index);
    
  });
  
}
<ul class="list2">
    <li>Text</li>
    <li>Text</li>
    <li>Text</li>
    <li>Text</li>
    <li>Text</li>
</ul>
Ason
  • 79,264
  • 11
  • 79
  • 127