views:

27

answers:

2
var $container = $('div#myContainer');
var $panels = $('div#myContainer > div');

Is it possible to reuse the selector I've already cached in $container within the next child selector?

+1  A: 

Yes!

var $container = $('div#myContainer');
var $panels = $('div', $container);

This makes use of the additional context argument with the standard jQuery() function. You can read up on it here: http://api.jquery.com/jQuery/#jQuery1

You could also do this.

var $container = $('div#myContainer');
var $panels = $container.find('div');
jessegavin
This doesn't use the "parent > child" selector though, correct? In a quick firebug test it seems to be selecting way too many elements.
macca1
Good call. As always, Nick Craver's answer is better than mine. ;(
jessegavin
I believe your first example works with var $panels = $(' > div', $container);
macca1
+2  A: 

You can do:

var $container = $('div#myContainer');
var $panels = $container.children('div');

This selects only the children like you have currently, using it as the context argument actually calls .find() internally, finding all descendants instead of only direct children.

Nick Craver
`$('> div', $container)` works too.
Crescent Fresh
@Crescent - True, but it's far less efficient, getting child nodes and checking them against a selector is a much faster operation than a `.find()` :)
Nick Craver
Just making sure readers understand that `find` does not mean recursive descent, it can work on direct children too. The way your answer reads (to me) places that into doubt :)
Crescent Fresh
@Crescent - It does find all descendants as the answer says **then** filters for only direct children. So yes, it definitely can work, but it's less efficient because it takes a much longer/broader/kinda round-about way to get the set.
Nick Craver