There's no need to require a big library like jQuery to accomplish this, if you don't want to. To achieve this with built-in DOM manipulation, get a collection of the li
siblings in an array, and on click, check the indexOf
the clicked element in that array.
const lis = [...document.querySelectorAll('#wizard > li')];_x000D_
lis.forEach((li) => {_x000D_
li.addEventListener('click', () => {_x000D_
const index = lis.indexOf(li);_x000D_
console.log(index);_x000D_
});_x000D_
});
_x000D_
<ul id="wizard">_x000D_
<li>Step 1</li>_x000D_
<li>Step 2</li>_x000D_
</ul>
_x000D_
Or, with event delegation:
const lis = [...document.querySelectorAll('#wizard li')];_x000D_
document.querySelector('#wizard').addEventListener('click', ({ target }) => {_x000D_
// Make sure the clicked element is a <li> which is a child of wizard:_x000D_
if (!target.matches('#wizard > li')) return;_x000D_
_x000D_
const index = lis.indexOf(target);_x000D_
console.log(index);_x000D_
});
_x000D_
<ul id="wizard">_x000D_
<li>Step 1</li>_x000D_
<li>Step 2</li>_x000D_
</ul>
_x000D_
Or, if the child elements may change dynamically (like with a todo list), then you'll have to construct the array of li
s on every click, rather than beforehand:
const wizard = document.querySelector('#wizard');_x000D_
wizard.addEventListener('click', ({ target }) => {_x000D_
// Make sure the clicked element is a <li>_x000D_
if (!target.matches('li')) return;_x000D_
_x000D_
const lis = [...wizard.children];_x000D_
const index = lis.indexOf(target);_x000D_
console.log(index);_x000D_
});
_x000D_
<ul id="wizard">_x000D_
<li>Step 1</li>_x000D_
<li>Step 2</li>_x000D_
</ul>
_x000D_