What does the $() function do in JavaScript?

The $() method is not part of the JavaScript language. It is often defined in JavaScript frameworks such as jQuery and Prototype, as a DOM selector.

It is interesting to note that up to until December 2009, the ECMAScript specification used to state:

The dollar sign ($) and the underscore (_) are permitted anywhere in an identifier. The dollar sign is intended for use only in mechanically generated code. (Source)

However this "dollar sign for mechanically generated code" hint was removed from the current ECMAScript specification (ECMA 262 - 5th Edition / December 2009).


Nevertheless, the original question was probably referring to the popular DOM selectors in jQuery, Prototype, et al. Here are a few jQuery examples:

$('*');         /* This selector is a wild card method and will select all 
                   elements in a document. */

$('#id');       /* This selector selects an element with the given ID. */

$('.class');    /* The class selector will gather all elements in the 
                   document with the given class name. */

$('element');   /* This selector will collect all elements in a document with 
                   the given tag name i.e. table, ul, li, a etc. */

You may want to check the following article for more examples:

  • jQuery selectors and examples

Answering to your question, this function return the DOM object with the specified ID.

For example, if you have on your HTML:


<div id="thisIsMyDivId">This is some content</div>

You can get the DIV element using:


var myDiv = $('thisIsMyDivId');

The idea of this function is to replace the necessity of use document.getElementById to do this.

And......repeating what everyone here already did...It is not a native JS function, it is implemented on some Frameworks (Prototype and jQuery AFAIK).


I think you're dealing with a framework here. Most frameworks include $ functions to generate custom objects from a selector or dom object.


That's not part of ECMAScript (JavaScript). It's just a function defined by some library of yours. Usually jQuery or PrototypeJS.

Tags:

Javascript