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

Stuck!: On the next line, use jQuery to select all list items (li) in an unordered list (ul) with the class of 'nav'?

I am stuck with this code:

On the next line, use jQuery to select all list items (li) in an unordered list (ul) with the class of 'nav'?

Why does $("[class='nav'] li") not work?

1 Answer

hey Albert Ko , just think about how you would select these in typical css. first you may select the unordered list (ul) - then, as you may only want to select the ul's that have the class nav you would add the class to the ul (ul.nav) - at the end you want to select the list items (li) in that unorered list called nav, so you add this as well - this would result in a selector that looks like this: ul.nav li
If you now put this into jquery you might end up here: $("ul.nav li"); and if doing so that sould help you pass the challenge ;)

thank you very much alex! regarding your code, why is there no space between 'ul' and '.nav' though? Would the string 'ul .nav' still function in the same way? It seems more natural since '.nav' is the selector for the class with a value of 'nav'...

Albert Ko,

ul .nav

could work, but the problem is that not only will this select the ul with a class of 'nav', it will also select all other unordered lists, which could be problematic if you have more than one ul on a page.

The goal is to always be as specific as possible to avoid these issues.

When there is no space between the ul and .nav, it means we are selected only an unordered list with the class of 'nav'. It won't select any other ul on the page, and it won't select any other element with the class of 'nav' like a div. Which is exactly what you want. I hope that is clear why you would want to write it out as

ul.nav

that way we are being very specific as to what we want.

I can't edit that reply, but I wanted to add that

ul .nav

would also select another element that has a class of nav, like a div as well.

Hey Albert,

$("ul.nav li"); would work. But when you're approach a problem like this, it'd be helpful to think about the HTML elements you're intending to select.

The HTML that the question asks looks very similar like this: <ul class="nav"> <li></li> <li></li> </ul>