-1

How do I write a simple for loop to iterate over span elements and assign each one a color from an array in an indexical order? So the B will be red, the E orange etc.

const colors = ['red', 'orange', 'yellow', 'green'];
    <h1>
        <span>B</span>
        <span>E</span>
        <span>A</span>
        <span>R</span>
    </h1>
Ren
  • 19
  • 3
  • 2
    What have you tried/researched so far? – Robson Aug 20 '21 at 00:03
  • Which color, specifically? Familiarize yourself with the [DOM API](//developer.mozilla.org/docs/Web/API/Document_Object_Model), with [how to access and process nested objects, arrays or JSON](/q/11922383/4642212) and use the available static and instance methods of [`Array`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array#Static_methods). – Sebastian Simon Aug 20 '21 at 00:05
  • I should've been more specific with my question. Lets say I want to assign the first span element the first color in the array, the second, the second from the array etc. I'm still very new to JS. The most challenging aspects for me are usually getting everything to work together (e.g. referencing a JS array to influence elements in html markup) – Ren Aug 20 '21 at 00:28
  • `Array.from(document.querySelector("h1").children)` is an array of these ``s. Look through the [`forEach`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) examples. The second argument is the index. You’ll need [the `%` operator](//developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Remainder). – Sebastian Simon Aug 20 '21 at 00:38

2 Answers2

1

You can first try getting all the elements using Document.querySelectorAll() then loop through them using Array.prototype.forEach() to set the color using Math.random().

Try the following way:

const colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];
//get all the elements
const elements = document.querySelectorAll('h1 > span');
//declare an array to store all the used colors
const usedColors = [];
//loop through all the elements
elements.forEach(function(span){
  //get color randomly from the array
  var c = colors[Math.floor(Math.random()*colors.length)];
  //check if the color is already used and loop to get new color
  while(usedColors.includes(c)){
    //take another color from the array
    c = colors[Math.floor(Math.random()*colors.length)];
  }
  //push to the used color array
  usedColors.push(c);
  //set the color to the element
  span.style.color = c;
});
<h1>
    <span>B</span>
    <span>E</span>
    <span>A</span>
    <span>R</span>
</h1>

Update: It seems simpler using the index like the following way:

const colors = ['red', 'orange', 'yellow', 'green'];
//get all the elements
const elements = document.querySelectorAll('h1 > span');
//loop through all the elements
elements.forEach(function(span, i){
  //set the color to the element using index i
  span.style.color = colors[i];
});
<h1>
    <span>B</span>
    <span>E</span>
    <span>A</span>
    <span>R</span>
</h1>
Mamun
  • 66,969
  • 9
  • 47
  • 59
  • 1
    I suggest you add some links about `querySelectorAll()` and `forEach()` to help OP learn – Rojo Aug 20 '21 at 00:05
  • Adding onto @ Rojo's suggestion, maybe extract the random colour logic into a separate function or document it for the same reason? – futur Aug 20 '21 at 00:07
  • Thanks for the suggestions, I think I have plenty of content on querySelector() and forEach(). My main problems with JS is getting everything to work. – Ren Aug 20 '21 at 00:30
  • @Ren, added another answer based on the update you made in the question, please check:) – Mamun Aug 20 '21 at 00:44
  • @Mamun very nice, thank you. It's interesting that your solution includes a function. I was trying to solve without one. Again, thank you! – Ren Aug 20 '21 at 19:43
0

//I declared a variable 'abc' to be the span tags.

const abc = document.querySelectorAll('span');

//Basically Iterating over each span tag and the array of colours and assigning them to each other.

   for (let index = 0; index < abc.length; index++){
     abc[index].style.color = colors[index];}

This should work

  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 11 '22 at 17:56