Get the Index of a Child node using JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 23, 2022

banner

Check out my new book

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 that contains the child elements of the element the property was accessed on.

We have to convert the HTMLCollection to an array to be able to use the Array.indexOf method.

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 is used to exit the loop to avoid unnecessary work.

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.

Use the search field on my Home Page to filter through my more than 3,000 articles.