I have to change color of list items using array colors.
Elements to modify.
<ul >
<li >1</li>
<li >2</li>
<li >3</li>
</ul>
const colorArray = ["red", "yellow", "blue"];
Basicly I've try to loop through list__items and then loop through colorArray and match item[currIndex].style.backgroundColor = colorArray[index] but every time got err.
If any one can give me advice how to solve it I will be appreciate.
<ul >
<li >1</li> <!-- color red-- >
<li >2</li><!-- color yellow-- >
<li >3</li><!-- color blue-- >
</ul>`
CodePudding user response:
You can use a data-attribute
to store the desired color of a list item.
Loop through the items and set the color of each item to the saved color, something like:
document.querySelectorAll(`ul.list li`)
.forEach(li => li.style.color = li.dataset.color);
<ul >
<li data-color="red">1 red</li>
<li data-color="yellow">2 yellow</li>
<li data-color="blue">3 blue</li>
</ul>
CodePudding user response:
const listItems = document.querySelectorAll('.list__item');
const colorArray = ["red", "yellow", "blue"];
for (let i = 0; i < listItems.length; i ) {
listItems[i].style.backgroundColor = colorArray[i];
}
<html>
<head>
<style>
.list__item {
display: inline-block;
width: 50px;
height: 50px;
border: 1px solid black;
text-align: center;
}
</style>
</head>
<body>
<ul >
<li >1</li>
<li >2</li>
<li >3</li>
</ul>
I suggest using the querySelectorAll
method. You can select all of the li
elements with the list__item
class, and then use a for loop to iterate over the elements and change their background color with style
.