K
K
Konstantin Maslennikov2021-07-05 10:23:59
JavaScript
Konstantin Maslennikov, 2021-07-05 10:23:59

How to get the li index when clicking on a link?

Hello!

You need to get the li index when clicking on a link inside it.
Without using jquery.

Such a structure:

<ul>
  <li>
    <a href="#">Link 1</a>
  </li>
  <li>
    <a href="#">Link 2</a>
  </li>
  <li>
    <a href="#">Link 3</a>
  </li>
  <li>
    <a href="#">Link 4</a>
  </li>
  <li>
    <a href="#">Link 5</a>
  </li>
</ul>

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander, 2021-07-05
@kosta6832

document.querySelectorAll('ul li a').forEach((link, index) => {
   link.addEventListener('click', () => {
       console.log('Index is', index);
   });
});

or
document.querySelectorAll('a').forEach(link => {
   link.addEventListener('click', event => {
       const parent = event.target.closest('li');
       if (parent !== null) {
           const items = [...parent.parentElement.children];
           const index = items.indexOf(parent);
           console.log('Index is', index);
       }
   });
});

T
TRNER, 2021-07-05
@TRNER

For this you can use parentElement
https://codepen.io/Turbin/pen/oNWbgRe

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question