Disguy
Disguy

Reputation: 39

Instead of using $(this) what else can I use?

I have the following code I want to edit:

$('.tab').click(function() {
    $(this).addClass('active').siblings().removeClass('active');
});

Instead of using $(this), why can't I do the following:

$('.tab').click(function() {
    $('.tab').click(function().addClass('active').siblings().removeClass('active');
});

If that is never going to work, how can I recreate the initial code without having to use $(this)?

Upvotes: 0

Views: 51

Answers (2)

Jordan Soltman
Jordan Soltman

Reputation: 3883

Not entirely sure why you want to do this, but here is a way to avoid using "this".

$(".tab").click(function(ev){
    $(ev.currentTarget).addClass('active').siblings().removeClass('active');
});

Upvotes: 1

Travis J
Travis J

Reputation: 82287

$('.tab') refers to all elements with class="tab", $(this) refers to the one element with class="tab" that was just clicked.

For more information on this in jQuery, see jQuery: What's the difference between '$(this)' and 'this'?

Upvotes: 0

Related Questions