Categories
JavaScript Answers

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

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *