Answer the question
In order to leave comments, you need to log in
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
document.querySelectorAll('ul li a').forEach((link, index) => {
link.addEventListener('click', () => {
console.log('Index is', index);
});
});
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);
}
});
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question