I saw some code around the web that uses the following statement
if ($($(this)).hasClass(\"footer_default\")) {
$(\'#abc\')
.appendTo($(this))
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)
.
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');
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.
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)
.
There is no meainig of doing that.
The following code return the same:
console.log($($(this)).hasClass("footer_default"))
console.log($(this).hasClass("footer_default"))
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/
$(this)
and $($(this))
both return jquery object.
There is no difference between these two.