Get the nth child of an Element using JavaScript

avatar
Borislav Hadzhiev

Last updated: Mar 4, 2024
4 min

banner

# Table of Contents

  1. Get the nth child of an Element using JavaScript
  2. Get the nth child of an Element using NodeList.item
  3. Get every nth child of an Element using querySelectorAll
  4. Get the Index of a Child node using JavaScript

# Get the nth child of an Element using JavaScript

Use the querySelector() method to get the nth child of an element.

The :nth-child pseudo-class returns the element that matches the provided position.

Here is the HTML for the examples.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>bobbyhadz.com</title> </head> <body> <div id="parent"> <div class="child1">Child 1</div> <div class="child2">Child 2</div> <div class="child3">Child 3</div> </div> <script src="index.js"></script> </body> </html>
The code for this article is available on GitHub

And here is the related JavaScript code.

index.js
const third = document.querySelector('#parent :nth-child(3)'); console.log(third); // ๐Ÿ‘‰๏ธ div.child3 const odd = document.querySelectorAll('#parent :nth-child(odd)'); console.log(odd); // ๐Ÿ‘‰๏ธ [div.child1, div.child3]

get nth child of element using javascript

The code for this article is available on GitHub

The first example uses the document.querySelector() method and the :nth-child() pseudo-class to select the third child of an element with an id of parent.

The :nth-child() pseudo-class takes a single argument that describes which elements should be matched.

Note that element indices are 1-based when using :nth-child().

You can narrow things down by only matching an element of a specific type, e.g. the second positioned div element.

index.js
const second = document.querySelector('#parent div:nth-child(2)'); console.log(second); // ๐Ÿ‘‰๏ธ div.child3

This selector would only match the second div element in the group of siblings.

# Get the nth child of an Element using NodeList.item

An alternative approach is to get a NodeList containing the children and use the NodeList.item() method to get a node from the list by index.

index.js
const children = document.getElementById('parent').children; console.log(children); // ๐Ÿ‘‰๏ธ [div.child1, div.child2, div.child3] const firstChild = children.item(0); console.log(firstChild); // ๐Ÿ‘‰๏ธ div.child1

get nth child of element using nodelist item

The code for this article is available on GitHub

We accessed the children property on the parent and got a NodeList containing the children of the element.

This allows us to use the item() method, to which we can pass the zero-based index of the element we want to select.

The item() method returns a node from a NodeList by index. If the index is out of range, a null value is returned.

Using the item method is more intuitive, however, the :nth-child() pseudo-class takes different keyword values, which makes it more flexible:

  • odd - matches the siblings whose numeric position is odd - 1, 3, 5, etc.
  • even - matches the siblings whose numeric position is even - 2, 4, 6, etc.
  • 3n - matches elements in position 3, 6, 9, 12, etc.

# Table of Contents

  1. Get every nth child of an Element using querySelectorAll
  2. Get the Index of a Child node using JavaScript

# Get every nth child of an Element using querySelectorAll

The following examples use document.querySelectorAll to select multiple elements using the :nth-child() pseudo-class.

index.js
const even = document.querySelectorAll( '#parent :nth-child(even)', ); console.log(even); // ๐Ÿ‘‰๏ธ [div.child2] const odd = document.querySelectorAll('#parent :nth-child(odd)'); console.log(odd); // ๐Ÿ‘‰๏ธ [div.child1, div.child3] const every2 = document.querySelectorAll( '#parent :nth-child(2n)', ); console.log(every2); // ๐Ÿ‘‰๏ธ [div.child2]

get every nth child of element using queryselectorall

The code for this article is available on GitHub

The third example selects every 2 elements, e.g. elements in positions 2, 4, 6, etc.

Note that indexes are 1-based when using :nth-child() and zero-based when using the item() method.

# 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.

index.html
<!DOCTYPE html> <html lang="en"> <head> <title>bobbyhadz.com</title> <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>
The code for this article is available on GitHub

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

get index of child node using javascript

The code for this article is available on GitHub

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

index.js
const child3 = document.getElementById('child3'); // ๐Ÿ‘‡๏ธ HTMLCollection(4)ย [p, p, p#child3, p, child3: p#child3] console.log(child3.parentElement.children);

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.

You can also use the spread syntax (...) to convert the collection of elements to an array.

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

The spread syntax (...) unpacks the collection of child elements into an array so we can call the Array.indexOf() method.

# Get the Index of a Child node using a for loop

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

get index of child node using for loop

The code for this article is available on GitHub

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.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev