Get nth-child using querySelector in JavaScript


Borislav Hadzhiev

Tue Dec 28 20212 min read


Photo by Yuvraj Singh

Get nth-child using querySelector in JavaScript #

To get the nth-child of an element using the querySelector method, pass the :nth-child() pseudo-class as a parameter to the method, e.g. document.querySelector('#parent :nth-child(1)'). The nth-child pseudo-class returns the element that matches the specified position.

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"> <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>

And here is the related JavaScript code.

const first = document.querySelector('#parent :nth-child(1)'); console.log(first); // ๐Ÿ‘‰๏ธ div.child1 const second = document.querySelector('#parent :nth-child(2)'); console.log(second); // ๐Ÿ‘‰๏ธ div.child2 const third = document.querySelector('#parent :nth-child(3)'); console.log(third); // ๐Ÿ‘‰๏ธ div.child3

The :nth-child() pseudo-class allows us to match elements based on their position among a group of siblings.

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

Note that with :nth-child(), element indices are 1-based.

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

const first = document.querySelector('#parent div:nth-child(1)'); console.log(first); // ๐Ÿ‘‰๏ธ div.child1

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

You can also pass different keyword values to the :nth-child() pseudo class, for example:

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

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

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

The querySelectorAll method returns a NodeList containing the elements that satisfy the condition.

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