macca1
macca1

Reputation: 9681

Reuse cached selector inside a child selector

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?

Upvotes: 2

Views: 500

Answers (2)

Nick Craver
Nick Craver

Reputation: 630489

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.

Upvotes: 3

jessegavin
jessegavin

Reputation: 75650

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');

Upvotes: 1

Related Questions