Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 337
MegaMatt Avatar asked Nov 22 '25 08:11

MegaMatt


2 Answers

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

That should do what you are looking for.

like image 129
Daniel A. White Avatar answered Nov 23 '25 21:11

Daniel A. White


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

like image 43
Brian Mains Avatar answered Nov 23 '25 21:11

Brian Mains



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!