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");
}

Answers:

Answer

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);
});
Answer

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");

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.