Categories
JavaScript Answers

How to Get the Indexes of Child Nodes with JavaScript?

Spread the love

Sometimes, we want to get the indexes of child nodes with JavaScript.

In this article, we’ll look at how to get the indexes of child nodes with JavaScript.

Use the Array.from Method

We can use the Array.from method to convert the node list object with the list of selected elements to an array.

Then we can use the array to get the index of the element.

For instance, if we have the following HTML:

<div>
  foo
</div>
<div>
  bar
</div>
<div>
  baz
</div>

Then we can get the divs and the indexes of them by writing:

const divs = document.querySelectorAll('div')
const arr = Array.from(divs)
for (const [index, div] of arr.entries()) {
  console.log(index, div)
}

We call document.querySelectorAll with the div.

Then we call Array.from with divs to convert the node list to an array.

Next, use the for-of loop with arr.entries to return an array with the arrays of the index of each div and the div object itself.

index has the index, and div has the div.

Use the Spread Operator

Another way to convert the node list into an array is to use the spread operator.

For instance, if we have the following HTML:

<div>
  foo
</div>
<div>
  bar
</div>
<div>
  baz
</div>

Then we can write:

const divs = document.querySelectorAll('div')
const arr = [...divs]
for (const [index, div] of arr.entries()) {
  console.log(index, div)
}

And we get the same result as before.

We just replaced Array.from with the spread operator.

Conclusion

To get the indexes of child elements with JavaScript, we convert the node list with the selected elements into an array.

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 *