dcsmith926 dcsmith926 - 4 months ago 9
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:

$($($('.breadcrumbs')[0]).children().last()).html("...");


I've never seen the
$
(
jQuery
) 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
this
, so I don't see why one would need nested calls to
$
.

Answer

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

$('.breadcrumbs').first().children().last().html("...");
Comments