1

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)
1
  • What is the value of n? Is it simply the ID? Does it include a trailing space character? These details will make a difference. Commented Jan 5, 2011 at 21:50

3 Answers 3

6

Try this:

var $n = $('#' + n); 
var $child = $(":nth-child(2)", $n);
Sign up to request clarification or add additional context in comments.

3 Comments

Note to OP: you'll see the $ in front of variables that represent jQuery objects. This is a nice convention.
Personally, I hate the $ in front of variables for jQuery objects. Maybe it just reminds me too much of PHP.
Because of the way jQuery implements selector context it may be faster to use $($n).find(':nth-child(2)'); Albeit I suspect the difference is likely to be minor, at best.
1

Another way:

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

2 Comments

If 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.
I think I liked this solution better because it's a little more self-documenting. More obvious what the selector is doing.
1

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.

3 Comments

Using .filter() won't necessarily return the same result as his original selector since it doesn't include children. A subsequent action on second might not work the same as an action on the original $n.
@jamietre: Unless the structure changes, it would be the same. Either the # + 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.
I was slowly coming to that understanding when your comment appeared :) True, I was thinking about the question more generally not in the context of nth-child.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.