Phill
Phill

Reputation: 546

Combining jQuery selectors with 'this'

I'm having some trouble combining these two specific selectors, whereas I don't have the same issue with simple selectors.

This is what I usually use (combining .btn and .toggle):

$(".btn, .toggle").removeClass("on");

These are the two I cannot combine (trying to combine this and the #toggle + id attr):

$(this).addClass("on");
$("#toggle" + $(this).attr("id")).addClass("on");

To be clear, I'm trying to combine the above 2 selectors as they do the same thing (adding the class), here's the full code.

$(".btn").click(function() {
    $(".btn, .toggle").removeClass("on"); 
    $(this).addClass("on");
    $("#toggle" + $(this).attr("id")).addClass("on");
})

And what I'm trying, that doesn't work:

$(this, "#toggle" + $(this).attr("id")).addClass("on");

Is there a special way I need to do this? Thanks.

Upvotes: 1

Views: 266

Answers (2)

Daniel A. White
Daniel A. White

Reputation: 190943

I think you need a , #

 $("#toggle, #" + $(this).attr("id")).addClass("on");
 //        ^ change here

Upvotes: 2

kapa
kapa

Reputation: 78681

You can use .add() to add elements to a collection:

$(this).add($("#toggle" + $(this).attr("id"))).addClass("on");

Or in a more readable way:

var toggleId = "#toggle" + $(this).attr("id");
var $toggleElem = $(toggleId);
$toggleElem.add(this).addClass('on');

Please note that in this example, the variable $toggleElem itself is not modified, it still contains only one element.

Upvotes: 4

Related Questions