Enlico
Enlico

Reputation: 28416

jQuery's dollar syntax vs dollar sign JavaScript "convention"

I've read here that for JavaScript there's a "convention" that the $ function be defined as a shortcut for document.getElementById, so I've defined the following function in a <script>,

function $(x) { return document.getElementById(x); }

so I could write $('main') instead of document.getElementById('main'), for instance.

Soon after, when I started looking into jQuery, I found that jQuery uses the syntax $(selector).action() extensively.

However, the two solutions don't seem to work nicely together.

Are indeed the two mutually exclusive? As in, if I use jQuery, I can't use the $ function above, and if I use the latter I can't use jQuery?

Upvotes: 1

Views: 67

Answers (1)

Spectric
Spectric

Reputation: 31992

You can use jQuery.noConflict to return control of $. Then, to use jQuery, use jQuery instead of $.

jQuery.noConflict();
jQuery('#main')

You can also assign the returned value of noConflict to an object, and use it just like $:

var a = jQuery.noConflict();
a('#main')

Upvotes: 2

Related Questions