change color using JavaScript (DOM)

147
March 02, 2022, at 9:00 PM
 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...!

Answer 1

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 class="box"></div>
<div class="box"></div>
<div class="box"></div>

Answer 2

It's working

<html>
 <body>
     <p id="p">
       on click change my color
     </p>
    <script>
      onclick = function(){
         document.getElementById("p").style.color = "#fff";
        document.getElementById("p").style.background = "#000";
      }
    </script>
  </body>
  </html>
Rent Charter Buses Company
READ ALSO
CSS Flex item spanning two rows without fixed height

CSS Flex item spanning two rows without fixed height

I am trying to create a flex container layout whereby one of the flex items should span two rowsSee image below for a better explanation:

173
create a notification/alert at a specific time html css angular

create a notification/alert at a specific time html css angular

i created a notification box that it shows me an alert when i create a notification from the date which i create this notification

110
&quot;page-break-before: always&quot; not working as intended after updating chrome from v97 to v98

"page-break-before: always" not working as intended after updating chrome from v97 to v98

https://cbbanalyticscom/stats/27694/games/1864019/overview - page-break-before is not working as intended on this page following chrome update from v97 to v98

122