I'm wondering if I can change the background color of a class when it has a specific value.
Example: if the element contains '1' change bg-color to red, if it contains '2' change bg-color to green, etc.
HTML:
<div class="skill-points"> 1 </div> <!-- BG color = red -->
<div class="skill-points"> 2 </div> <!-- BG color = green -->
<div class="skill-points"> 3 </div> <!-- BG color = yellow -->
CSS:
.skill-points {
width: 50px;
padding: 4px;
margin: 4px;
border: 1px solid #000;
text-align: center;
}
How should I write my JavaScript code to accomplish this effect?
You can get all your relevant class elements in a collection (using getElementsByClassName) and then convert it to an array (using spread operator). You can then assign background colours using style.backgroundColor property.
I have used a mapping object, that can be useful otherwise you can do individual if checks too. innerText is the property you can use to compare the inner Text of the HTML elements.
let mapping = {
'1' : 'red', '2' : 'green' , '3': 'blue' };
[...document.getElementsByClassName('skill-points')].forEach( x => {
x.style.backgroundColor = mapping[x.innerText];
});
.skill-points {
width: 50px;
padding: 4px;
margin: 4px;
border: 1px solid #000;
text-align: center;
}
<div class="skill-points"> 1 </div> <!-- BG color = red -->
<div class="skill-points"> 2 </div> <!-- BG color = green -->
<div class="skill-points"> 3 </div>
Just loop through your elements, check the innerText, and set the element style.
document.querySelectorAll('.skill-points').forEach(div => {
if (div.innerText.contains('1')) div.style.backgroundColor = 'red';
...
});
1) You can get text using textContent and match it and set the color as
const allSkillPoints = document.querySelectorAll(".skill-points");
allSkillPoints.forEach(el => {
const text = +el.textContent.trim();
if (text === 1) el.style.backgroundColor = "red";
else if (text === 2) el.style.backgroundColor = "green";
else if (text === 3) el.style.backgroundColor = "yellow";
})
.skill-points {
width: 50px;
padding: 4px;
margin: 4px;
border: 1px solid #000;
text-align: center;
}
<div class="skill-points"> 1 </div>
<!-- BG color = red -->
<div class="skill-points"> 2 </div>
<!-- BG color = green -->
<div class="skill-points"> 3 </div>
<!-- BG color = yellow -->
2) You can also make use of Map here as:
const allSkillPoints = document.querySelectorAll(".skill-points");
const map = new Map()
map.set(1, "red")
.set(2, "green")
.set(3, "yellow");
allSkillPoints.forEach(el => {
const text = +el.textContent.trim();
el.style.backgroundColor = map.has(text) ? map.get(text) : "white";
})
.skill-points {
width: 50px;
padding: 4px;
margin: 4px;
border: 1px solid #000;
text-align: center;
}
<div class="skill-points"> 1 </div>
<!-- BG color = red -->
<div class="skill-points"> 2 </div>
<!-- BG color = green -->
<div class="skill-points"> 3 </div>
<!-- BG color = yellow -->