The following line of code comes from the official dialog/#modal-form example
allFields = $( [] ).add( name )
Could someone please clarify what $( [] )
does? Is it the same as $("*")
?
Another thing puzzled me is that I did not see allFields
being added/appended to anywhere/any object, it is only created and modified. Am I missing something?
$() = window. jQuery() $()/jQuery() is a selector function that selects DOM elements. Most of the time you will need to start with $() function. It is advisable to use jQuery after DOM is loaded fully.
jQuery selectors are used to "find" (or select) HTML elements based on their name, id, classes, types, attributes, values of attributes and much more. It's based on the existing CSS Selectors, and in addition, it has some own custom selectors.
Description. "$("div p")" Selects all elements matched by <div> that contain an element matched by <p>.
$([])
creates an empty jQuery object, just like $()
. $('*')
creates a jQuery object which holds all elements which match the CSS selector *
, which every element will match.
In other words, $([])
gets nothing, $('*')
gets everything.
If you take a look at the doco for the jQuery()
function - usually seen as the shorthand version $()
- you'll see that it accepts several different types and combinations of parameters.
The syntax you asked about:
$([])
is the jQuery( elementArray )
syntax which lets you pass an array of DOM elements where the return will be a jQuery object wrapping those elements. By passing an empty array you basically get an empty jQuery object (just as you would if you passed a selector string that didn't match anything, but without the inefficiency of trying to find a match first).
When created allFields
has three DOM elements added to it (where name
, email
and password
are created just before that as jQuery objects containing one DOM element each):
allFields = $( [] ).add( name ).add( email ).add( password )
Presumably the advantage of adding the individual items rather than just doing:
allFields = $("#name,#email,#password")
is that the individual objects for each element were also needed and would've been created anyway, so no need to bother reselecting them via a query string.
Another thing puzzled me is that I did not see
allFields
being added/appended to anywhere/any object, it is only created and modified, am I missing something?
It is referred to in two other places in the code:
allFields.removeClass( "ui-state-error" );
// and, later
allFields.val( "" ).removeClass( "ui-state-error" );
This is fairly standard jQuery usage to remove a class or set the value of all elements in the jQuery object. No need for it to be added to some other object.
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