Last updated: Mar 4, 2024
Reading timeยท4 min
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.
<!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>
And here is the related JavaScript code.
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]
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.
:nth-child()
.You can narrow things down by only matching an element of a specific type, e.g.
the second positioned div
element.
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.
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.
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
We accessed the children
property on the parent and got a NodeList
containing the children of the element.
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.The following examples use document.querySelectorAll
to select multiple
elements using the :nth-child()
pseudo-class.
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]
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.
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.
<!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>
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.
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.
-1
is returned.You can also use the spread syntax (...) to convert the collection of elements to an array.
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.
for
loopAlternatively, 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.
You can learn more about the related topics by checking out the following tutorials: