Home > Mobile >  change color using JavaScript (DOM)
change color using JavaScript (DOM)

Time:02-08

 const box = document.getElementsByClassName('box');
 let colorAsString = '#FEC6F0';
 let colorAsNumber = #FEC6F0;
    Array.from(box).forEach((element) =>{
        element.style.backgroundColor = colorAsString;
        element.style.backgroundColor = colorAsNumber;
    });

I stored a hex-color value in string as well as a number and pass the variable as a value for css property. Why this code not work can you explain me...!

CodePudding user response:

When you edit the style property, it is in the end only a CSS string. So to represent colors you can use formats like: '#ffffff' or 'rgb(255,255,255)'. But you cannot use a number.

You can read more about that here: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style

 const box = document.getElementsByClassName('box');
 let colorAsString = '#FEC6F0';
    Array.from(box).forEach((element) =>{
        element.style.backgroundColor = colorAsString;
    });
.box {
  width:100px;
  height:100px;
  margin:10px;
  background-color:gray;
}
<div ></div>
<div ></div>
<div ></div>

CodePudding user response:

try it

  <html>
   <body>
   <p id="p" style="color:red">
    on click change my color
   </p>
<script>
    onclick = function() {
        document.getElementById("p").style.color = "green";
    }
</script>
</body>
</html>
  •  Tags:  
  • Related