Get the Index of a Child node using JavaScript

avatar

Borislav Hadzhiev

Mon Jan 03 20222 min read

Get the Index of a Child node using JavaScript #

To get the index of a child node:

  1. Use the Array.from() method to convert the children collection to an array.
  2. Use the indexOf() method to get the index of the child node.
  3. The indexOf() method returns the first index at which an element can be found in the array.

Here is the HTML for the examples in this article.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="parent"> <p>Child 1</p> <p>Child 2</p> <p id="child3">Child 3</p> <p>Child 4</p> </div> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
const child3 = document.getElementById('child3'); const index = Array.from( child3.parentElement.children ).indexOf(child3); console.log(index); // ๐Ÿ‘‰๏ธ 2

The children property returns an HTMLCollection which contains the child elements of the element the property was accessed on.

To be able to use the Array.indexOf method, we have to convert the HTMLCollection to an array.

The indexOf method takes a value and tries to locate it in the array.

If the value is found, its index is returned from the method, otherwise -1 is returned.

Alternatively, you can use a simple for loop to achieve the same result.

index.js
const parent = document.getElementById('parent'); const children = parent.children; let index = -1; for (let i = 0; i < children.length; i++) { if (children[i].id === 'child3') { index = i; break; } } console.log(index); // ๐Ÿ‘‰๏ธ 2

We used a for loop to iterate over the collection of children.

On each iteration, we check if the id attribute of the current child is equal to child3.

If the condition is met, we assign the current index to the index variable and use the break keyword to break out of the for loop.

The break keyword exits the iteration, which prevents us from continuing to iterate after we've found the result.

The index variable is initialized to -1 to mimic the behavior of the indexOf method, however you can adjust it depending on your use case.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee