Arseny
Arseny

Reputation: 5179

How to add class to a jQuery element if a condition is true and remove the same class if the condition is false?

Is there a shorter way to do the following?

var select_all_checkbox = $("input.select_all");
var is_checked = select_all_checkbox.prop("checked");

if (is_checked) {
    select_all_checkbox.parent().addClass("selected");
} else {
    select_all_checkbox.parent().removeClass("selected");
}

Upvotes: 25

Views: 13728

Answers (2)

Felix Kling
Felix Kling

Reputation: 816322

Use toggleClass, passing a second argument (a boolean) that specifies whether the class should be added or not:

select_all_checkbox.parent().toggleClass("selected", is_checked);

If you have multiple elements selected by input.select_all, you have to iterate over them though:

$("input.select_all").each(function() {
    $(this).parent().toggleClass('selected', this.checked);
});

Upvotes: 45

Arseny
Arseny

Reputation: 5179

Absolutely! You can choose between the methods (addClass/removeClass) programmatically, and use the one that is returned when an expression is executed.

Like this:

var select_all_checkbox = $("input.select_all");
var is_checked = select_all_checkbox.prop("checked");

select_all_checkbox.parent()[is_checked ? "addClass" : "removeClass"]("selected");

Upvotes: 3

Related Questions