How to get child node index with JavaScript?

Sometimes, we want to get child node index with JavaScript.

In this article, we’ll look at how to get child node index with JavaScript.

How to get child node index with JavaScript?

To get child node index with JavaScript, we can use the Array.from method.

For instance, we write

const index = Array.from(element.parentNode.children).indexOf(element);

to get the child nodes of element with element.parentNode.children.

Then we convert it to an array with Array.from.

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

Conclusion

To get child node index with JavaScript, we can use the Array.from method.