dcsmith926 dcsmith926 - 11 months ago 36
Javascript Question

Is there any reason to have nested calls to $ (jQuery)?

I was poking around the source code of a website when I came across some code like this:

$($('#newForm_step1')).hide("slide", { direction: "left" }, 0);

and this:


I've never seen the
) function used this way, and I was wondering if there'd be any practical reason to do something like this? To the best of my knowledge, wrapping a jQuery object with a call to
simply returns a jQuery object for the same selector, and methods on jQuery objects return
, so I don't see why one would need nested calls to


No, there is no reason to do this.

In the first example, $($(...)) is redundant. There is absolutely no effect in immediately wrapping a jQuery object in another jQuery object.

The line should read

$('#newForm_step1').hide("slide", { direction: "left" }, 0);

In the second example, $(...)[0] returns a raw DOM element, so it's wrapped again before having jQuery's .children().last() invoked on it. The result of that is already a jQuery object, so there is no need to re-wrap it, and the "unwrapping" could have been avoided by calling .first() instead of [0].

The line should read