Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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");
}
like image 882
Arseny Avatar asked Apr 07 '14 23:04

Arseny


People also ask

How add or remove a class in jQuery?

addClass() - Adds one or more classes to the selected elements. removeClass() - Removes one or more classes from the selected elements. toggleClass() - Toggles between adding/removing classes from the selected elements.

Has class with if condition in jQuery?

jQuery hasClass() Method The hasClass() method checks if any of the selected elements have a specified class name. If ANY of the selected elements has the specified class name, this method will return "true".

What is add class in jQuery?

The addClass() method adds one or more class names to the selected elements. This method does not remove existing class attributes, it only adds one or more class names to the class attribute. Tip: To add more than one class, separate the class names with spaces.

Which jQuery function is used to remove an existing class from the Element?

removeClass() Remove a single class, multiple classes, or all classes from each element in the set of matched elements.


1 Answers

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);
});
like image 187
Felix Kling Avatar answered Oct 12 '22 09:10

Felix Kling