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)
Try this:
var $n = $('#' + n);
var $child = $(":nth-child(2)", $n);
$($n).find(':nth-child(2)'); Albeit I suspect the difference is likely to be minor, at best.Another way:
$n = $('#' + n);
$n.find(":nth-child(2)");
n is just an ID like "myID", then the original selector looks like "#myID:nth-child(2)", which doesn't include the descendant selector. In that case, using .find() is different from the original. We can't really know for sure without knowing the value of n.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.
second might not work the same as an action on the original $n.# + n element is an :nth-child(2) or it isn't. It is just odd to specify nth-child on an element when there can be only one on the page.
n? Is it simply the ID? Does it include a trailing space character? These details will make a difference.