3

I need to take the colors of the "child" elements from the "parent" element and make a linear gradient out of them, and then insert it into the "gradient" element. In the alert, my style background-color is repeated several times. How do I fix this?

function myFunction() {
  var gradientcolor = "";
  var childcolor = document.getElementById("parent").children;
  var i;
  for (i = 0; i < childcolor.length; i++) {
    gradientcolor += childcolor[i].style.backgroundColor + ', ';
    console.log(gradientcolor);
    document.getElementById("gradient").style.backgroundImage = "linear-gradient(to right, " + gradientcolor + " )"
  }
}
<div id="parent">
  <div id="child" style="width:50px;height:50px;background-color:rgb(255, 0, 0);"></div>
  <div id="child" style="width:50px;height:50px;background-color:rgb(0, 215, 0);"></div>
  <div id="child" style="width:50px;height:50px;background-color:rgb(0, 0, 255);"></div>
</div>
<div id="gradient" style="width:150px;height:50px;background-color:#f2f2f2"></div>

<button onclick="myFunction()">Try it</button>

4
  • mplungjan thanks for editing, some code solution to work?
    – maja
    May 17, 2020 at 9:05
  • yes. A standard and an ES6 one
    – mplungjan
    May 17, 2020 at 10:29
  • I lake Amit Kumar answer because it is simple and does not deviate from the source code. The error in the code was a GradientImage and an incorrectly placed comma.
    – maja
    May 17, 2020 at 15:08
  • The only change I made to your HTML in example 1 was to give the child a class. Your HTML is invalid if you have multiple IDs that are the same. Amit was the last to point out the comma was the problem. I expect you to want to use the corrected example instead of a "me too" answer
    – mplungjan
    May 17, 2020 at 16:33

3 Answers 3

2

you need to remove trailing , sign at the end of the gradientcolor variable and set the background on the gradient element outside of the for loop

function myFunction() {

  let gradientcolor = "";
  let childcolor = document.getElementById("parent").children;

  for (let i = 0; i < childcolor.length; i++) {
    gradientcolor += childcolor[i].style.backgroundColor + ', ';
  }

  document.getElementById("gradient").style.background = "linear-gradient(to right, " + gradientcolor.slice(0, -2) + " )"
}
<div id="parent">
  <div id="child" style="width:50px;height:50px;background-color:rgb(255, 0, 0);"></div>
  <div id="child" style="width:50px;height:50px;background-color:rgb(0, 215, 0);"></div>
  <div id="child" style="width:50px;height:50px;background-color:rgb(0, 0, 255);"></div>
</div>
<div id="gradient" style="width:150px;height:50px;background-color:#f2f2f2"></div>

<button onclick="myFunction()">Try it</button>

1
  • It is background, not background image
  • you have a trailing comma, that makes the final statement not work.
  • you need to move the assignment outside the loop - although it still works, you now assign the string 3 times
  • Also, although you do not use them, IDs need to be unique

If you use an array and push, you do not get weird commas either:

function myFunction() {
  var gradientcolor = []; // create an array
  var childcolor = document.getElementById("parent").children;
  var i;
  for (i = 0; i < childcolor.length; i++) {
    gradientcolor.push(childcolor[i].style.backgroundColor); // add to the array
  }
  // this join concatenates all array items with a comma - 
  // using comma is actually default so not even needed
  const statement = "linear-gradient(to right, " + gradientcolor.join(",") + " )"; 
  console.log(statement)
  document.getElementById("gradient").style.background = statement
}
<div id="parent">
  <div class="child" style="width:50px;height:50px;background-color:rgb(255, 0, 0);"></div>
  <div class="child" style="width:50px;height:50px;background-color:rgb(0, 215, 0);"></div>
  <div class="child" style="width:50px;height:50px;background-color:rgb(0, 0, 255);"></div>
</div>
<div id="gradient" style="width:150px;height:50px;background-color:#f2f2f2"></div>
<button onclick="myFunction()">Try it</button>

ES6 version without inline script and css. Gave the child divs a class of child and changed the ID to be unique

window.addEventListener("load", () => { // when the page loads
  document.getElementById("tryIt").addEventListener("click", () => { // when the specific button is clicked
    const gradientcolor = [...document.querySelectorAll("#parent .child")]   // creating an array from the HTMLElementCollection
      .map(child => getComputedStyle(child).getPropertyValue('background-color')); // grabbing the background-color from each
    document.getElementById("gradient").style.background = `linear-gradient(to right, ${gradientcolor.join(",")})`; // using template literal to wrap the string around the joined array
  })
})
.child {
  width: 50px;
  height: 50px;
}

#c1 {
  background-color: rgb(255, 0, 0);
}

#c2 {
  background-color: rgb(0, 215, 0);
}

#c3 {
  background-color: rgb(0, 0, 255);
}

#gradient {
  width: 150px;
  height: 50px;
  background-color: #f2f2f2
}
<div id="parent">
  <div class="child" id="c1"></div>
  <div class="child" id="c2"></div>
  <div class="child" id="c3"></div>
</div>
<div id="gradient"></div>
<button type="button" id="tryIt">Try it</button>

6
  • 2
    Why the downvote? Downvotes without explanations are USELESS to me and to OP
    – mplungjan
    May 17, 2020 at 9:10
  • What do you want to know?Is there anything useful here in this forum?
    – user11323942
    May 17, 2020 at 9:15
  • 1
    @Giulio what do you mean? It is the first time I play with gradients. If there is something wrong with the code I suggest, then I would love to know so I can write a better answer for OP to get the best solution
    – mplungjan
    May 17, 2020 at 9:21
  • I think any explanation is welcome. the code works.. mplungjan I would ask you if you can explain a little how to get rid of the for{} not repeating, join end other? thank you
    – maja
    May 17, 2020 at 9:24
  • you still have inline css in es6 version of the code. You can remove the inline css and use getComputedStyle(child).getPropertyValue('background-color') to get the value of background-color
    – Yousaf
    May 17, 2020 at 9:48
1

The issue was with extra comma added by your code in th linear-gradient function arguement which made the value invalid. Hence no gradient.

Try to debug this type of issue on your own by putting breakpoint in js code, will make you better developer each day.

Changing the code below which works.

function myFunction() {
  var gradientcolor = "";
  var childcolor = document.getElementById("parent").children;
  var i;
  for (i = 0; i < childcolor.length; i++) {
    gradientcolor += ', ' + childcolor[i].style.backgroundColor;
    document.getElementById("gradient").style.background = "linear-gradient(to right " + gradientcolor + " )";
  }
  
}
<div id="parent">
  <div id="child" style="width:50px;height:50px;background-color:rgb(255, 0, 0);"></div>
  <div id="child" style="width:50px;height:50px;background-color:rgb(0, 215, 0);"></div>
  <div id="child" style="width:50px;height:50px;background-color:rgb(0, 0, 255);"></div>
</div>
<div id="gradient" style="width:150px;height:50px;background-color:#f2f2f2"></div>

<button onclick="myFunction()">Try it</button>

3
  • You can keep inside also, no issue there. It's just that having gradient color property finalized and then applying to element. If you requirement says to fill color one by one you can.
    – Amit Kumar
    May 17, 2020 at 9:28
  • You can check now, moved inside. Change was just extra comma at end nothing else.
    – Amit Kumar
    May 17, 2020 at 9:31
  • Actually while i was changing it that solution was not there and wheni submitted i saw almost similar answer was there.
    – Amit Kumar
    May 17, 2020 at 9:39

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.