Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript indexOf a list for a targeted event in a unordered list giving the wrong index

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading