I have a server generated template that contains multiple elements with ids book_cat_id, book_cat_id2 etc that I need to find and change their inline background colours to match corresponding categories
data-cat_label="Fiction" can have any one of the categories Fiction, Fantasy, Comic, History, Technical
Is there is more efficient way of doing this for multiple colours?
const colors = {
fiction: "#ff7477",
fantasy: "#7dbb65",
technical: "#BC9DCA",
comic: "#00A2E0",
history: "#ff0099",
health: "#f59e2e"
}
let id1 = book_cat_id.getAttribute("data-cat_label");
let id2 = book_cat_id2.getAttribute("data-cat_label");
if(id1 === 'Fiction') {
book_cat_id.style.backgroundColor = colors.fiction;
}else if (id1 === 'Fantasy') {
book_cat_id.style.backgroundColor = colors.fantasy;
}else if (id1 === 'Comic') {
book_cat_id.style.backgroundColor = colors.comic;
}else if (id1 === 'History') {
book_cat_id.style.backgroundColor = colors.history;
}
if(id2 === 'Fiction') {
book_cat_id2.style.backgroundColor = colors.fiction;
}else if (id2 === 'Fantasy') {
book_cat_id2.style.backgroundColor = colors.fantasy;
}else if (id2 === 'Comic') {
book_cat_id2.style.backgroundColor = colors.comic;
}else if (id2 === 'History') {
book_cat_id2.style.backgroundColor = colors.history;
}
<table>
<tr>
<td id="book_cat_id" data-cat_label="Fiction" style="background-color:#ff0000;">
Book
</td>
</tr>
<tr>
<td id="book_cat_id2" data-cat_label="Fantasy" style="background-color:#ff0000;">
Book
</td>
</tr>
</table>
book_cat_id.style.backgroundColor = ({'History': colors.history, 'Fantasy': colors.fantasy})[id1] ;add keys as needed.book_cat_id.style.backgroundColor = colors[id1.toLowerCase()], assuming all of the possible labels are present as keys incolors...