I am trying to get the index number of a ‘li’ element of a ‘ul’ from the html.
To do this I change the ‘ul’ into a list to get his children with:
[...ul.children]
However when I target any of the children I get a -1 as index instead of the correct index.
How to fix?
Is this due to the fact that the list items it’s not empty and has a div or other elements inside?
Here is my javascript and my html:
const ul = document.querySelector('ul');
ul.addEventListener('click', myFunc);
function myFunc(e) {
const indexToShow = [...ul.children].indexOf(e.target);
console.log(indexToShow);
console.log(e.target);
}
<ul class="calendar-list">
<li class="list-item">
<div class="fight-link">
<span class="date">1 Dec 2022</span>
<span class="fighters-name">JAY</span>
</div>
</li>
<li class="list-item">
<div class="fight-link">
<span class="date">2 Dec 2022</span>
<span class="fighters-name">Jo</span>
</div>
</li>
<li class="list-item">
<div class="fight-link">
<span class="date">3 Dec 2022</span>
<span class="fighters-name">Bob</span>
</div>
</li>
</ul>
>Solution :
The click evennt triggers on the span, but you’re comparing against the li.
So you’ll need to search for the li using closest() to match the elements:
const ul = document.querySelector('ul');
ul.addEventListener('click', myFunc);
function myFunc(e) {
const indexToShow = [...ul.children].indexOf(e.target.closest('li'));
console.log(indexToShow);
}
<ul class="calendar-list">
<li class="list-item">
<div class="fight-link">
<span class="date">1 Dec 2022</span>
<span class="fighters-name">JAY</span>
</div>
</li>
<li class="list-item">
<div class="fight-link">
<span class="date">2 Dec 2022</span>
<span class="fighters-name">Jo</span>
</div>
</li>
<li class="list-item">
<div class="fight-link">
<span class="date">3 Dec 2022</span>
<span class="fighters-name">Bob</span>
</div>
</li>
</ul>