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

Alexander D
Alexander D
8,461 Points

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
MOD
rydavim
Treehouse Moderator 16,897 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!

Alexander D
Alexander D
8,461 Points

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
Treehouse Moderator 16,897 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!