Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set colors from array to multiple elements

I have an array containing some colors. I also have a div with some child elements. What I'm trying to accomplish is that each child element will get a color from the array. I'm close, and I can console log the colors, but at the moment the child's get assigned the last color in the array.

var colors = ["#e57373", "#ba68c8", "#90caf9", "#4db6ac", "#dce775", "#ffb74d", "#b0bec5", "#81c784"];
var setColors = customizeContainer.childNodes;
for (var i = 1; i < setColors.length; i += 2) {
	for (var x = 0; x < colors.length; x++) {
		setColors[i].style.backgroundColor = colors[x];
	}
}

  <div id="customizeMenu" class="col l12">
    <div class="col l1"></div>
    <div class="col l1"></div>
    <div class="col l1"></div>
    <div class="col l1"></div>
    <div class="col l1"></div>
    <div class="col l1"></div>
    <div class="col l1"></div>
    <div class="col l1"></div>
    <div class="col l1"></div>
  </div>

enter image description here

like image 543
Sander Hellesø Avatar asked Jun 25 '26 08:06

Sander Hellesø


1 Answers

Here is a solution that will loop the colors once they are all used.

var colors = ["#e57373", "#ba68c8", "#90caf9", "#4db6ac", "#dce775", "#ffb74d", "#b0bec5", "#81c784"];
var customizeContainer = Array.from(document.querySelectorAll('#customizeMenu > div'));

customizeContainer.forEach(function(node, i) {
    node.style.backgroundColor = colors[i % colors.length];
});
#customizeMenu>div {
  width: 2em;
  height: 2em;
  display: inline-block;
}
<div id="customizeMenu" class="col l12">
  <div class="col l1"></div>
  <div class="col l1"></div>
  <div class="col l1"></div>
  <div class="col l1"></div>
  <div class="col l1"></div>
  <div class="col l1"></div>
  <div class="col l1"></div>
  <div class="col l1"></div>
  <div class="col l1"></div>
</div>

The problem with your code was that you were looping over all the colors and assigning them for each node. So they all got the last color.

Another problem (that you mentioned in the comments) about the nodes being every 2 is because the childNodes returns text nodes and comments as well. So you either need to use children or use document.querySelectorAll to select the wanted elements directly.

like image 54
Gabriele Petrioli Avatar answered Jun 27 '26 21:06

Gabriele Petrioli



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!