JavaScript jQuery Basics Understanding jQuery Events and DOM Traversal What is Traversal?

How to target a different list with J Query

Hello there,

I am trying to target a different list on this codepen I created:

Specifically, I am trying to target the second Li item of the second list, and make it yellow.

I can target the first or second list using the following code:

$("ul").eq(1).css({color: "yellow"})

If I change 1 to 0, I target the first list. However this will target the entire list. How can I target any item inside the second list, without recurring to the following code?

$("li").eq(5).css({color: "yellow"})

Thanks, Alex

1 Answer

Treehouse Moderator 18,106 Points

If I'm understanding your question correctly, you just need to chain more than one selector together. It's really simple to do this using jQuery by putting a space between each selector.

// In this case, you could use the class selector and then get all the list items.
// This will only get list items which are in the elements list. 
$(".elements li").eq(1).css({color: "yellow"})

Remember - you can always use more than one element selector when creating a jQuery object with $.

If you still have any questions though, just let me know. Happy coding!

Thanks rydavim! Can I ask you an extra question? What If I didn't have the class "elements" to help me out to target the second list, and I had two blank UL lists without class or ID, how would I target the second element, inside the second list?

Treehouse Moderator 18,106 Points

Okay, so I hadn't actually used eq() before and didn't realize you could basically use it as a pseudo-class. So you could just put it in that first selector and pick whichever ul and li you wanted to grab.

// You can use :eq() in the creation of your jQuery object.
$("ul:eq(1) li:eq(1)").css({color: "yellow"})

That's probably a cleaner way to do it anyway. Good question!