Search code examples
javascriptjquerychaining

How does jQuery act on multiple selectors?


I've been wondering for a little while how jQuery acts on multiple selectors. For instance:

$("p").css({"border":"1px solid #000"});

Performs the subsequent function on all p tags. I've had a look through the jQuery source but to be honest it's an extensive read when you're trying to work out one specific bit of functionality. My assumption is that there's some kind of stack whereby css() and other functions merely act on the current stack, which is divined by the selector function.

Other than that, I can't work out how it could be replicated as, I think, there's no way in javascript to return multiple objects to execute a function on. E.g.

House.first_bedroom.size = "large"
House.second_bedroom.size = "small"
House.all_rooms().alertSize();

alertSize() would have to be a member function of some collection of objects rather than a member function of each room object that is returned by all_rooms()?


Solution

  • First, jQuery functions (generally) return a jQuery object, which acts like an array and keeps track of the current set of matched elements. Second, internally each jQuery function makes extensive use of the each() function to iterate over the matched objects, perform subsequent actions and construct the new jQuery object to return. Some functions do return something other than jQuery, like get(). These functions cannot be chained. Chaining is only possible when the function returns a jQuery object. Because the returned object is a jQuery object it has all the functions of jQuery available to it.