HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

removeClass and addClass optimization in a scoring system

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
addclassremoveclassscoringsystemoptimizationand

Problem

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 >= successRatio) {
    $(".bkf").removeClass("label-success");
    $(".bkf").removeClass("label-warning");
    $(".bkf").removeClass("label-important");
    $(".bkf").addClass("label-success");
}

else if (bodyPercent >= 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");
}

Solution

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 >= successRatio) {
    bkf.addClass("label-success");
}
else if (bodyPercent >= warningRatio) {
    bkf.addClass("label-warning");
}
else {
    bkf.addClass("label-important");
}

Code Snippets

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

Context

StackExchange Code Review Q#12530, answer score: 8

Revisions (0)

No revisions yet.