removeClass and addClass optimization in a scoring system I have scoring system where I want to change icon color by changing CSS classes.

How can I optimize this jQuery? After testing, I found this the only alternative, but I trust there is a more simplified method.

// Count scores
$('#bodyScore').text((90 / myarray.length) * bodyScore + '/90'); 

// Change icon color
var bodyPercent  = bodyScore / myarray.length;
var successRatio = 0.9;
var warningRatio = 0.5;

if (bodyPercent &gt;= successRatio) {
    $(".bkf").removeClass("label-success");
    $(".bkf").removeClass("label-warning");
    $(".bkf").removeClass("label-important");
    $(".bkf").addClass("label-success");
}

else if (bodyPercent &gt;= warningRatio) {
    $(".bkf").removeClass("label-success");
    $(".bkf").removeClass("label-warning");
    $(".bkf").removeClass("label-important");
    $(".bkf").addClass("label-warning");
}

else {
    $(".bkf").removeClass("label-success");
    $(".bkf").removeClass("label-warning");
    $(".bkf").removeClass("label-important");
    $(".bkf").addClass("label-important");
}
Both the removeClass and addClass methods will accept a space-separated list of class names to add/remove, and both can be chained.

You can cache the selector so you don't have to repeatedly search the DOM.

And since you remove the same three classes in each branch of execution, you can move that outside of the if/else if/else:

var bkf = $(".bkf").removeClass("label-success label-warning label-important");
if (bodyPercent &gt;= successRatio) {
    bkf.addClass("label-success");
}
else if (bodyPercent &gt;= warningRatio) {
    bkf.addClass("label-warning");
}
else {
    bkf.addClass("label-important");
}