admcfajn
admcfajn

Reputation: 2108

Can I use $(this) along with a css selector in jQuery?

Can I use $(this) along with a css selector?

For example, if I want to do the following:

$(".toggle-nav").on("click", function(){
    $(".nav").toggleClass("active");
    $(this).toggleClass("active");
});

Is there any way that be shortened to the following or anything similar?

$(".toggle-nav").on("click", function(){
    $(this|".nav").toggleClass("active");
});

I know I could do this or something similar:

$(".toggle-nav").on("click", function(e){
    element = e.currentTarget;
    // get selector from e.currentTarget ...
    $("#"+element.id+",.nav").toggleClass("active");
});

But is there a jQuery way to do it?

Upvotes: 0

Views: 44

Answers (1)

gurvinder372
gurvinder372

Reputation: 68393

Is there any way that be shortened to the following or anything similar?

Use jquery add

$(this).add( ".nav" ).toggleClass("active");

Upvotes: 5

Related Questions