What does the $()
function do in the following example?
function test(){
var b=$('btn1');
eval(b);
}
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").
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.
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.
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.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With