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

Time:12-16

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 >
  <li >
    <div >
      <span >1 Dec 2022</span>
      <span >JAY</span>
    </div>
  </li>
  <li >
    <div >
      <span >2 Dec 2022</span>
      <span >Jo</span>
    </div>
  </li>
  <li >
    <div >
      <span >3 Dec 2022</span>
      <span >Bob</span>
    </div>
  </li>
</ul>

CodePudding user response:

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 >
  <li >
    <div >
      <span >1 Dec 2022</span>
      <span >JAY</span>
    </div>
  </li>
  <li >
    <div >
      <span >2 Dec 2022</span>
      <span >Jo</span>
    </div>
  </li>
  <li >
    <div >
      <span >3 Dec 2022</span>
      <span >Bob</span>
    </div>
  </li>
</ul>

CodePudding user response:

here is how you can achive this

const ul = document.querySelector('ul');
  ul.addEventListener('click', myFunc);

  function myFunc(e) {
    const indexToShow = [...ul.children].indexOf(e.path[2]);
    console.log(indexToShow);
    console.log(e.target);
  }
  • Related