What does $($(this)) mean?
I saw some code around the web that uses the following statement
if ($($(this)).hasClass("footer_default")) {
$('#abc')
.appendTo($(this))
.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
$($('selector')[0])
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
document.querySelector('selector');
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")) {
$('#abc')
.appendTo($this)
.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.