MegaMatt
MegaMatt

Reputation: 23763

Using jQuery objects in jQuery selectors

I'm fairly new to jQuery, and think I might be making something harder than it needs to be. I've got a jQuery variable that is just an unordered list. It was declared this way:

var $list = $('#activityList'); // activityList is ID of <ul>

I'm trying to select all <li> elements within that list using the variable I've created:

$items = $('#' + $list.attr('id') + ' > li');

Does anyone know if there's a different syntax to achieve the same thing without having to break the variable down to it's id attribute?

Thanks.

Clarification: I used simplified code for the purposes of asking the question, but I do want to make use of the jQuery variable "$list" within the selector, rather than hardcoding the ID.

Upvotes: 2

Views: 300

Answers (4)

Brian Mains
Brian Mains

Reputation: 50728

$("#activitylist > li") would work, as > traverses content. You can also use, with $list as a JQuery object:

$list.find("li") or $list.children("li") to find the list items as well. children would be more efficient if you are only looking for immediate children.

Upvotes: 3

theraccoonbear
theraccoonbear

Reputation: 4337

Maybe I'm misunderstanding, but what's wrong with...

var $items = $('#activityList > li'); 

Upvotes: 0

Kyle
Kyle

Reputation: 4366

Try this:

var items = $('#activityList > li');

Upvotes: 1

Daniel A. White
Daniel A. White

Reputation: 190905

$items = $('li', $list); 

That should do what you are looking for.

Upvotes: 5

Related Questions