More code depends on $() referring to document than you might think.
Whenever no context is passed in to a jQuery object, the context is
set to 'document'. That way when you do a .find(), it'll actually find
some relevant elements. Since $() has no context, the context then
defaults to document. Same with doing $("").
If you want an empty set, $([]) is the preferred solution (it's what I
would use, too).
All that being said, however, I somehow suspect that the result that
you're trying to achieve could be done much more easily, in another
way. Can you post your full code for us to look at? I don't think I've
ever seen a true need to have an empty jQuery set returned.
--John
On 2/16/07, Danny Wachsstock <[EMAIL PROTECTED]> wrote:
>
> Yes, $('nonexistent-selector') works, but seems very inelegant. I think $([])
> is the best solution, but I'd like to hear from the gurus. How much code
> depends on $() referring to document?
>
>
>
> Sam Collett wrote:
> >
> > On 16/02/07, Danny Wachsstock <[EMAIL PROTECTED]> wrote:
> >>
> >> I've been using jQuery for a few months now, trying to convert all my
> >> hand-rolled javascript and came across a minor problem that I could not
> >> find
> >> documented anywhere:
> >> I want to create DOM elements and add them into a jQuery object, as in;
> >>
> >> var result = [empty jQuery object];
> >> $.each(...
> >> var element = ...;
> >> result.add(element);
> >> );
> >>
> >> But how to create an empty jQuery? Scouring the source code, I eventually
> >> hit upon $([]), but this is nowhere documented. Is there a better way?
> >> Is there a good reason $() should return $(document) rather than an empty
> >> jQuery?
> >>
> >> Daniel Wachsstock
> >> http://youngisrael-stl.org
> >>
> >> --
> >
> > I found that out the hard way as well, so perhaps it should be
> > documented. I think searching for a class that does not exist (
> > $("atag.nonexistentclass") ) will also return an empty jQuery object.
> >
> > As for changing $() to not return $(document), that may be a bad idea
> > as it helps reduce the amount of code to write, plus may break some
> > plugins.
> >
> > _______________________________________________
> > jQuery mailing list
> > [email protected]
> > http://jquery.com/discuss/
> >
> >
>
> --
> View this message in context:
> http://www.nabble.com/Creating-an-empty-jQuery-object-tf3240592.html#a9010063
> Sent from the JQuery mailing list archive at Nabble.com.
>
>
> _______________________________________________
> jQuery mailing list
> [email protected]
> http://jquery.com/discuss/
>
_______________________________________________
jQuery mailing list
[email protected]
http://jquery.com/discuss/