Alex Rivera | Logout

The $ dollar sign

Asked 2009-07-24T21:21:30.803
41

I have something simple like this:

$(selector).append("somestuff");

But since I'm going to reuse the selector I cache it with:

var $selector = $(selector);

So I end up with:

$selector.append("somestuff");

My question is, should I be doing that, or should I be doing:

var selector = $(selector);
selector.append("somestuff");

Trying either one, both works. Which method is correct, and why? Is the $ in $selector unnecessary because the jquery object has already been declared in $(selector)?


Edit

Thanks for the answers. It seems very simple and quite clear. Still, there seems to be disagreement over whether or not I should use $ in the variable. It would be nice for everyone to vote up an answer. :)

Edit
Report

2 Answers

33

I've seen it done both ways. All you are doing is creating a variable with the name '$selector', so they are functionally equivalent. The nice thing about it is that it does make them easy to pick out as jQuery objects.

answered 2009-07-24T21:24:35.103
-2

"$" is a function in jQuery. So when you call $(selector), you're actually calling the function $ with selector as the argument.

Generally, don't use the "$" as part of a variable name for javascript. You will only confuse yourself.

answered 2009-07-24T21:26:20.730

Your Answer