Categories
JavaScript Answers

How to get an element’s nth-child element in JavaScript?

Spread the love

Sometimes, we want to get an element’s nth-child element in JavaScript.

In this article, we’ll look at how to get an element’s nth-child element in JavaScript.

How to get an element’s nth-child element in JavaScript?

To get an element’s nth-child element in JavaScript, we can use querySelector.

For instance, we write:

<section class="hardware">some text, nth-child is one</section>
<section class="hardware">some text, nth-child is two</section>
<section class="hardware">some text, nth-child is three</section>
<section class="hardware">some text, nth-child is four</section>
<section class="hardware">some text, nth-child is five</section>

to add 5 section elements.

Then we get the 2nd section element by writing:

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

We call document.querySelector with '.hardware:nth-child(2)' to get the 2nd section element with class hardware.

Therefore, child is <section class="hardware">some text, nth-child is two</section>.

Conclusion

To get an element’s nth-child element in JavaScript, we can use querySelector.

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 *