views:

134

answers:

4

Hi all,

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.

+4  A: 
$items = $('li', $list);

That should do what you are looking for.

Daniel A. White
Should actually be $('li', $list) - no # before the li. :)
Wesley Petrowski
@Wesley, thanks for the catch. I was wondering that myself.
Mega Matt
Also worth noting that you can pass either a jQuery object or a DOM object as the context.
Wesley Petrowski
Now will this answer get me only the `li` elements that are direct descendants, or will it retrieve all ancestors? What if I did this: `$items = $('> li', $list)`. Would that work?
Mega Matt
It will select items just like the normal context EXCEPT it will be filtered to only children and decendents of the *context*
Kevin Peno
Test case here: http://jsbin.com/ahida
Wesley Petrowski
also, `$list.find('li')` is equivalent
cobbal
+1  A: 

Try this:

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

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

var $items = $('#activityList > li');
theraccoonbear
Nothing is wrong with it, you just already **have** the context to search in (`$list`) so why not save some processing and start there? ;)
Kevin Peno
+3  A: 

$("#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.

Brian
+1 for find/children as it is functionality equivilant to the dominant answer.
Kevin Peno