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.
You can use
.add()to add elements to a collection:Or in a more readable way:
Please note that in this example, the variable
$toggleElemitself is not modified, it still contains only one element.