How to Get the Second Match of a Selector with document.querySelector?

Sometimes, we want to get the second match of a selector with the document.querySelector method.

In this article, we’ll look at how to get the second match of a selector with the document.querySelector method.

Get the Second Match of a Selector with document.querySelector

To get the second match of a selector with the document.querySelector method, we can use the nth-child pseudo-selector.

For instance, if we have:

<div class='titanic'>
  foo
</div>
<div class='titanic'>
  bar
</div>
<div class='titanic'>
  baz
</div>

Then we can select the 2nd element with class titanic by writing:

const second = document.querySelector('.titanic:nth-child(2)')
console.log(second)

We use nth-child(2) to select the 2nd match.

Therefore, second should be the div with ‘bar’ as the text content.

Conclusion

To get the second match of a selector with the document.querySelector method, we can use the nth-child pseudo-selector.