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.