Dave
Dave

Reputation: 1277

When to use $ in JS

This is a super newbie JS question, but am wondering how to use the '$' when writing JS. For instance, I wrote a very simple JS if statement:

if (document.getElementById('D').value == '') {document.getElementById('D').value = 0;}

However, I saw someone else write it like this:

if (document.getElementById('D').value == '') {$('D').value = 0;}

Does '$' equal 'document.getElementById'? What are best practices when using '$'? Thanks!

Upvotes: 0

Views: 122

Answers (4)

Deepak
Deepak

Reputation: 1

It is basically used for the insertion of jQuery in your html code.

Upvotes: 0

mnemotronic
mnemotronic

Reputation: 1026

The DOLLAR sign is shorthand for "jQuery". Anyplace you want to use a jQuery function you can substitute "$" for "jQuery".

... engage blithering idiot mode ...

I'm constantly referring to my copy of the O'Reilly jQuery Pocket Reference. That plus the docs on the jQuery site and the users on StackExchange make life easier. I still get tripped up when getting a single element from a jQuery function via brackets:

jQuery('div.topbar')[3]

That returns an HTML entity, not a jQuery object.

I use the debugger in Chrome a lot. I can do a ton of prototyping and POCs in the debugger before committing the work to code.

Upvotes: 0

wjohnsto
wjohnsto

Reputation: 4463

$ typically refers to jQuery. It is a widely used library that helps with DOM manipulation. Your second example would only work if you included jQuery in your project (or you defined $).

Upvotes: 0

Joel
Joel

Reputation: 324

$ is usually used with JQuery. When you include JQuery in your page you can shorten references to it by using $('some css selector') to use it. If you didn't include JQuery you shouldn't need to use the $.

Here is a tutorial to get started with jquery: W3Schools JQuery Tutorial.

They show some examples there.

Upvotes: 1

Related Questions