Categories
JavaScript Answers

How to find element index in container with JavaScript?

Spread the love

Sometimes, we want to find element index in container with JavaScript.

In this article, we’ll look at how to find element index in container with JavaScript.

How to find element index in container with JavaScript?

To find element index in container with JavaScript, we can use the spread operator and the indexOf method.

For instance, we write

const index = [...el.parentElement.children].indexOf(el);

to use el.parentElement.children to get all the child elements of the el element’s parent element.

Then we spread the node list to an array.

Next, we call indexOf with el to get the index of el in the array of elements.

Conclusion

To find element index in container with JavaScript, we can use the spread operator and the indexOf method.

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 *