ottz0 ottz0 - 6 months ago 18
jQuery Question

Adding classes to appending data

I am using

jQuery
and have some data that is coming in from a websocket. The data state is acknowledged,open and closed.

I am appending the data to a table

$(".incident-row").append(
"<tr><td>"+incident.data.id+"</td>"
+"<td>"+incident.data.state+"</td>"
+"<td>"+incident.data.brief+"</td>"
+'<td><button type="button" class="btn btn-primary btn-sm">View details</button></td>'
+"</tr>"
);


I now want to use bootstrap to add a green,gray or red background class to the state depending on the state itself. The class is attaching correctly but is overwriting the existing class with the new class in the
DOM


How can I rewrite this so each class stays on the effected row from the if statement?

if(incident.data.state === "OPEN"){
$('.incident-row tr').addClass("table-danger");
}
else if(incident.data.state === "ACKNOWLEDGED"){
$('.incident-row tr').addClass("table-active");
}
else if(incident.data.state === "CLOSED"){
$('.incident-row tr').addClass("table-success");
}
else{
return;
}

Answer

Your selector of $('.incident-row tr') is selecting all the incident rows.

You can use the contains selector.

$('.incident-row tr:contains("OPEN")').addClass("table-danger");
$('.incident-row tr:contains("ACKNOWLEDGED")').addClass("table-active");
$('.incident-row tr:contains("CLOSED")').addClass("table-success");