Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the $() function do in JavaScript?

Tags:

What does the $() function do in the following example?

function test(){
    var b=$('btn1');
    eval(b);
}
like image 898
odiseh Avatar asked Jan 30 '10 10:01

odiseh


People also ask

What does $() do in JavaScript?

The $() function The dollar function, $(), can be used as shorthand for the getElementById function. To refer to an element in the Document Object Model (DOM) of an HTML page, the usual function identifying an element is: document. getElementById("id_of_element").

What does $( function ()) short hand do?

It's just shorthand for $(document). ready() , as in: $(document). ready(function() { YOUR_CODE_HERE }); Sometimes you have to use it because your function is running before the DOM finishes loading.

What is the use of the $() function in jQuery?

When a jQuery object is passed to the $() function, a clone of the object is created. This new jQuery object references the same DOM elements as the initial one.

What does $() stand for in jQuery?

In jQuery, the $ sign is just an alias to jQuery() , then an alias for a function. This page reports: Basic syntax is: $(selector).action() A dollar sign to define jQuery. A (selector) to "query (or find)" HTML elements.


1 Answers

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
like image 146
Daniel Vassallo Avatar answered Sep 28 '22 06:09

Daniel Vassallo