0

I have to change the color of list items using array colors.

Elements to modify.

<ul class="list">
      <li class="list__item">1</li>
      <li class="list__item">2</li>
      <li class="list__item">3</li>
</ul>

const colorArray = ["red", "yellow", "blue"];

I've tried to loop through list__items and then loop through colorArray and match item[currIndex].style.backgroundColor = colorArray[index] but every time got err.

If anyone can give me advice on how to solve it I will appreciate it.

<ul class="list">
  <li class="list__item">1</li> <!-- color red-- >
  <li class="list__item">2</li><!-- color yellow-- >
  <li class="list__item">3</li><!-- color blue-- >
</ul>`

2 Answers 2

1

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 class="list">
  <li class="list__item" data-color="red">1 red</li>
  <li class="list__item" data-color="yellow">2 yellow</li>
  <li class="list__item" data-color="blue">3 blue</li>
</ul>

Sign up to request clarification or add additional context in comments.

1 Comment

By the time you've added an inline data-attribute you may as well have added an inline style
0

You can simply achieve this requirement by using the querySelectorAll and then iterate over it to apply the styles.

Live Demo :

const listItem = document.querySelectorAll('.list__item');

const colorArray = ["red", "yellow", "blue"];

listItem.forEach((item, index) => item.style.color = colorArray[index]);
<ul class="list">
  <li class="list__item">1</li>
  <li class="list__item">2</li>
  <li class="list__item">3</li>
</ul>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.