1 Answer
1

Edited to better address your question:First, look at the relevant code here, this is how jQuery handles the $() call. When you're passing a DOM element (which this is, it's the div itself) the context is the DOM element itself, this better allows handling of document fragments, etc. When you pass a string, the default context is document (because it's the top ancestor to search from). Remember a $(selector, context) is actually calling context.find(selector) under the covers, so it makes sense to start at document if nothing's specified.

Note: you can always check the context, it's an available property, like this: $(this).context

For the .add() behavior:.add() uses the same context for selecting as the jQuery element you're adding to, so what you're seeing is the expected behavior. For a better description, see how .add() is written:

Thanks for the answer. I think maybe I'm just not understanding the purpose/use of the context of a jQuery object. Why does $d have a context of #div1 in the first place instead of document?
–
user113716Apr 13 '10 at 2:00

1

@patrick - You can see how $(this) is handled here: github.com/jquery/jquery/blob/master/src/core.js#L59 When you do $(DOMElement) the context is that DOM element, just how it works. For example, you could be dealing with an element that's not in the DOM, in a document fragment for example, so document doesn't always work.
–
Nick Craver♦Apr 13 '10 at 2:07

@patrick - I re-read your post and re-wrote most of the answer to better address your main question, hopefully that clarifies it a bit more, let me know if it still leaves questions.
–
Nick Craver♦Apr 13 '10 at 2:16

OK, I think I'm getting it. So the reason jQuery assigns #div1 is that jQuery doesn't really know what the heck else to put there (without doing a traversal every time, I suppose). So overriding the context in $d is safe and irrelevant in terms of expected functionality.
–
user113716Apr 13 '10 at 2:19