I'm trying to understand how jQuery creates the return object when searching for DOM elements. I've gone through the source, but I'm not completely sure I understand, and was hoping somebody here could give me some insight.
From what I can gather reading the source, when querying for a jQuery DOM, jQuery finds matching DOM elements, and then adds the matched DOM element as an object using the index of the element as the key for the new object.
if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) {
for ( match in context ) {
// Properties of context are called as methods if possible
if ( jQuery.isFunction( this[ match ] ) ) {
this[ match ]( context[ match ] );
// ...and otherwise set as attributes
} else {
this.attr( match, context[ match ] );
}
}
}
return this;
Returning this
, is returning the entire jQuery object which includes all the methods. Have I got it right to this point?
Now, it appears all the functions like css,find,ajax,hide,etc. are in the jQuery.fn object.
Somehow (and I think this is where I'm not seeing it), these functions are called, not on the DOM element itself, but through the access.js https://github.com/jquery/jquery/blob/master/src/core/access.js
var access = jQuery.access = function( elems, fn, key, value, chainable, emptyGet, raw ) {
using css as an example, we have
jQuery.extend({
css: function( elem, name, extra, styles ) {...
jQuery.fn.extend({
css: function( name, value ) {
return access( this, function( elem, name, value ) {
var styles, len,
map = {},
i = 0;
if ( jQuery.isArray( name ) ) {
styles = getStyles( elem );
len = name.length;
for ( ; i < len; i++ ) {
map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles );
}
return map;
}
return value !== undefined ?
jQuery.style( elem, name, value ) :
jQuery.css( elem, name );
}, name, value, arguments.length > 1 );
What I think I'm missing is how did we get from calling $('div').css(...)
to that calling the jQuery.fn.extend.css method, and from there, the access method being called with a different signature to the access method initialized in the core jQuery?
Also, if we're constantly replacing the jQuery[0],jQuery[1]
, how is it that I can have:
var divs = $('div');
var spans = $('span');
Maintaining two different set of document tags if they are both returning the same jQuery object? I thought the object would be updated.
Am I completely misunderstanding how this is all working?