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 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:

https://codepen.io/DeMichieli/full/YodEKZ

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

rydavim
rydavim
18,813 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?

rydavim
rydavim
18,813 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!