Looking to retrieve the index number of an 'li' element within a 'ul' from the HTML structure. I attempted to convert the 'ul' into a list and access its children using:
[...ul.children]
However, upon targeting any of the children, I am receiving a -1 as the index instead of the correct index. How can this be resolved?
Could this issue be related to the presence of additional elements such as divs inside the list items?
Below is the JavaScript code snippet along with the corresponding HTML structure:
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>