<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>
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);
}
});
});