2

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.

2
  • why do you prefix your variables with $? Commented Dec 17, 2009 at 21:15
  • 2
    Because it makes it easier to identify jQuery objects withing a large block of js code. Commented Dec 17, 2009 at 21:25

4 Answers 4

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

That should do what you are looking for.

Sign up to request clarification or add additional context in comments.

5 Comments

Should actually be $('li', $list) - no # before the li. :)
Also worth noting that you can pass either a jQuery object or a DOM object as the context.
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?
It will select items just like the normal context EXCEPT it will be filtered to only children and decendents of the context
also, $list.find('li') is equivalent
3

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

1 Comment

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

Try this:

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

Comments

0

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

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

1 Comment

Nothing is wrong with it, you just already have the context to search in ($list) so why not save some processing and start there? ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.