Borislav Hadzhiev
Last updated: Jul 23, 2022
Check out my new book
To get the index of a child node:
Array.from()
method to convert the children collection to an array.indexOf()
method to get the index of the child node.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.
<!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.
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.
-1
is returned.Alternatively, you can use a simple for
loop to achieve the same result.
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
.
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.