I have an array of colors and then I randomized them. I want to assign different color to each list item instead of having items with the same colors or having repeated colors.
const myList = document.querySelector('.myList');
const listItems = myList.querySelectorAll('li');
const itemColors = ['red', 'green', 'royalblue', 'purple','cornflowerblue', 'sienna','palevioletred','orange'];
listItems.forEach((item, index) => {
let randomColors = itemColors[Math.floor(Math.random() * itemColors.length)];
item.style.color = randomColors;
});
<ul class="myList">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
<li>Soup</li>
<li>Juice</li>
<li>Beer</li>
<li>Wine</li>
<li>Soda</li>
</ul>
2
Answers
One idea is just clone your
itemColors
and then randomly sort.You can then use the index into this array to get the color.
Note: The random sort here is not 100% random as technically it’s not using sort in the correct way, but for something like this should be fine. Also this also assumes your array of colors is larger than the number of
li
elements.eg..
You can also make a Function that give you the unique index and hence you can assign the different color to each variable.
It’s just a method approach. If you are interested.
The HTML: