What does $($(this)) mean?


What does $($(this)) mean?

I saw some code around the web that uses the following statement
if ($($(this)).hasClass(“footer_default”)) {
.toolbar({position: “fixed”});

What is the use of $($(this)) and why is that necessary here?


Solution 1:

Yes, $($(this)) is the same as $(this), the jQuery() or $() function is wonderfully idempotent. There is no reason for that particular construction (double wrapping of this), however, something I use as a shortcut for grabbing the first element only from a group, which involves similar double wrapping, is


Which amounts to, grab every element that matches selector, (which returns a jQuery object), then use [0] to grab the first one on the list (which returns a DOM object), then wrap it in $() again to turn it back into a jQuery object, which this time only contains a single element instead of a collection. It is roughly equivalent to

document.querySelectorAll('selector')[0];, which is pretty much

Solution 2:

You can wrap $ as many times as you want, it won’t change anything.

If foo is a DOM element, $(foo) will return the corresponding jQuery object.

If foo is a jQuery object, $(foo) will return the same object.

That’s why $($(this)) will return exactly the same as $(this).

Solution 3:

There is no specific need for double-wrapping and $($(this)) is exactly the same as $(this).

That said, I once found this double-wrapping in one file in my project, committed by another developer. Tracking the changes through revision, turned out that it started as $($(this).find('selector').first()) – that is, the result of some selector was wrapped to create a new object. Then for whatever reasons, the selector was removed and only the double-wrapping of this remained. Needless to say, on the next commit it was changed to $(this).

Solution 4:

As explained before me, $($(this)) and $(this) are absolutely identical. jQuery returns the same jQuery object if you try to wrap it more than once.

Additionally, for performance considerations it is a good practice to reuse jQuery objects – it is quite expensive to create jQuery objects, especially the ones with complex selectors. Example:

var $this = $(this);
if ($this.hasClass("footer_default")) {
        .toolbar({position: "fixed"});

Just google for ‘jQuery best practices’ – it will take a 30 min for you to learn these basics and you will use jQuery way more effectively.

Solution 5:

There is no meainig of doing that.

The following code return the same:


a boolean value depenging on if the selected element has or not the class footer_default:

.hasClass( className )Returns: Boolean

Demo: http://jsfiddle.net/IrvinDominin/aSzFn/

Solution 6:

$(this) and $($(this)) both return jquery object.

There is no difference between these two.