Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Help with using querySelector to get nth-child

I tried to answer question 5 with a querySelector and couldn't get it to work. Is it possible for it to work? Here's what i tried:

```// 5: Select only the second element with the class '.container'.

// Assign it to a variable named container.

const container = document.querySelector('.container:nth-child(2)');

container.style.backgroundColor = "royalblue";```

1 Answer

Steven Parker
Steven Parker
231,533 Points

You forgot to include a link to the challenge so I'm having to guess a bit, but the "nth-child" function would only find a second element that has the same parent.

If the intention is to find the second element anywhere in the document, you'll need a different strategy.

My apologies, I thought they were automatically linked. (I'm having a hard time creating good questions too. As you can see, my attempt at using backticks to show code failed too)

https://teamtreehouse.com/library/introducing-the-practice-27

So from what I understand so far, this search won't work in this instance because the .container classes are children of different parents?

Steven Parker
Steven Parker
231,533 Points

The automatic links normally occur when you use the "get help" button to create the question. The backticks need to be on a line by themselves (or with just the language name for syntax coloring).

And yes, the "nth-child" counts only children of the same parent, plus it could also be thrown off by other elements (but that could be countered by using "nth-of-type" instead).

But for this exercise, you want a method that will find the second item on the page of that class, regardless of the nesting level.