4

Assume you have the following code:

function name() {
    $(this).css('background', 'red');
}

$('selector1').click(name);

$('selector2').click(function () {
    name.call($(this).parent());
});

Now, when the function is called by clicking on 'selector1' this is an HTML object and $(this) a jQuery object, but if the function is called by clicking on 'selector2' this is already a jQuery object so what is $(this)?

I know I could do something like name.call($(this).parent()[0]); to get an HTML object, but my question is what happens when you do something like $($(this)) or $($('selector'))? What is the result of that and, most impotently, is there any harm in using such a construct?

Korikulum
  • 2,529
  • 21
  • 25

1 Answers1

6

$(this) when this is already a jQuery object creates a copy of the jQuery object.

From the jQuery docs:

Cloning jQuery Objects

When a jQuery object is passed to the $() function, a clone of the object is created. This new jQuery object references the same DOM elements as the initial one.

Community
  • 1
  • 1
FishBasketGordo
  • 22,904
  • 4
  • 58
  • 91