Yeah, it dawned on me later that the chaining/no error thing was
behind the empty array. I think the no errors bit is overhyped,
though. Other than the $('#id').hide() example, you aren't going to
get very far when a selection fails, and it will make debugging a
little weird if you don't throw an error at some point. I can live
with it. It is the jQuery way. But would it be too much to just put in
an .exists() method like Hamish's in the core? It would add, what, a
dozen bytes, but it would eliminate a lot of these questions and, dare
I say, the code would look better semantically:

  if($('#id').exists())

Until then, I think .is() is clearer than .length. To each their own.
Both work, and choice is a good thing.


Dave Methvin wrote:
> > It isn't intuitive that jQuery always returns an array-like object.
>
> If jQuery didn't return a jQuery object, you would not be able to
> chain methods. Chaining is at the core of jQuery's design. In many
> cases you don't even need to "check if an id exists", since any
> following methods in the chain will operate on an empty jQuery object
> and do nothing:
>
> $("#someID").hide();
>
> If #someID exists, it will be hidden. If it doesn't exist, nothing
> will happen because the .hide() method will be applied to 0 DOM
> elements. Imagine if the $() method returned a null in those cases.
> Instead of chaining you'd have to do something like this:
>
> var myid = $("#someID");
> if ( myid )
>   myid.hide();
>
> Very, very, not like jQuery.
>
>
> > One assumes that a failed search returns nothing.
>
> It does return nothing. That's what a zero in the .length property
> or .size() method is telling you: "There are no selected DOM elements
> in this jQuery object."

Reply via email to