Phillip Senn
Phillip Senn

Reputation: 47595

How do you cache a variable in jQuery?

If I'm constantly referencing:

$('#' + n + ':nth-child(2)').val()

then how do I cache $('#' + n) into a variable?

$n = $('#' + n);
$n:nth-child(2)

Upvotes: 1

Views: 882

Answers (3)

user113716
user113716

Reputation: 322462

You need to use .filter(), which applies the selector to elements at the root of the jQuery object instead of .find() or the context parameter, which search inside the elements at the root.

var $n = $('#' + n);
var second = $n.filter(':nth-child(2)');

That is assuming that the initial selector in your question evaluates to something like:

$('#someID:nth-child(2)')

If it is, it would concern me a little since there should only be one element with someID.

To give a more certain answer, we would need to know the value of n.

Upvotes: 1

Jamie Treworgy
Jamie Treworgy

Reputation: 24334

Another way:

$n = $('#' + n);
$n.find(":nth-child(2)");

Upvotes: 1

Chandu
Chandu

Reputation: 82893

Try this:

var $n = $('#' + n); 
var $child = $(":nth-child(2)", $n);

Upvotes: 6

Related Questions