How to get index of element as child relative to parent with JavaScript?

Sometimes, we want to get index of element as child relative to parent with JavaScript.

In this article, we’ll look at how to get index of element as child relative to parent with JavaScript.

How to get index of element as child relative to parent with JavaScript?

To get index of element as child relative to parent with JavaScript, we can spread the node list returned by querySelectorAll into an array.

For instance, we write

const lis = [...document.querySelectorAll("#wizard > li")];

lis.forEach((li) => {
  li.addEventListener("click", () => {
    const index = lis.indexOf(li);
    console.log(index);
  });
});

to call querySelectorAll to select the li’s.

Then we spread the returned node list to an array with ...

Next, we call forEach on the lis array with a callback and call addEventListener on each li to add click listeners to each li.

Conclusion

To get index of element as child relative to parent with JavaScript, we can spread the node list returned by querySelectorAll into an array.