Modify the color with JavaScript by manipulating the Document Object Model (DOM)

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

I have two variables storing a hex-color value as a string and a number. I then use these variables as values for CSS properties on the elements with the class 'box'. Can someone explain why this code is not working for me?

Answer №1

Modifying the style attribute ultimately results in a CSS string. To specify colors, you can use formats such as '#ffffff' or 'rgb(255,255,255)'. However, plain numbers cannot be used for this purpose.

For further information, please refer to: 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

Success!

<html>
 <body>
     <p id="p">
       Click me to change my color
     </p>
    <script>
      onclick = function(){
         document.getElementById("p").style.color = "#fff";

        document.getElementById("p").style.background = "#000";
      }
    </script>
  </body>
  </html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When an ad call is successful in ajax, the response includes the usage of document

Currently, we are facing a challenge in loading an ad after an ajax load more. The ad call response contains document.write, which redirects to the ad itself once the call is made. Unfortunately, there is no straightforward method to only get the ad html a ...

What is the @page rule in Material-UI?

Trying to incorporate Material-UI styles with react-to-print to print components can be tricky, especially when dealing with a specific component that requires a particular page size. Here's an attempt at achieving this: const styles = (theme: Theme) ...

Guide on Adding a Map to a List in JavaScript

Currently, I am trying to extract data from a form and add it as a map to my list. However, an error message is displayed: Cannot read property 'url' of undefined express = require("express"); app = express(); var bodyParser = require("body- ...

How to retrieve an element using a dynamically generated class name in Vue.js

<v-data-table :headers="menuheaders" //this menus from api response :items="menus" item-key="usersmenu_menuid" items-per-page="1000" hide-default-footer="" class="elevation-1" > <template v-s ...

Unable to insert string into evaluated array

How do I use the eval definition to push a string into an array? jsn_obj=[{"row":1,"integerz":1,"stringz":"a"},{"row":2,"integerz":2,"stringz":"b"}]; var getz = jsn_obj; for (var i = 0, length = getz.length; i < length; i++) { console.l ...

Looking for a solution to a problem with your vertical CSS/jQuery dropdown menu

My web app features a vertical CSS menu that is working correctly except for one minor issue. When I mouse out on all elements with the class a.menutoggle, the last dropdown menu remains open. I am struggling to find a solution to hide it. Can someone plea ...

Is there a way to extract the headers as key-value pairs when converting a csv file to json using the csv-parser from the csv module?

I've been attempting to execute the code below, but for some reason it's not working as expected const reader = readFile(req.file, { headers: true }) // Utilize the readable stream api reader.on('data', function(data) { console.l ...

What methods do current web browsers utilize to implement the JS Array, particularly when it comes to adding

When using the .push() method on an Array object in JavaScript, the underlying "array" capacity increases as more elements are added. If anyone knows of a reliable resource for this type of information regarding JavaScript, please feel free to share. upda ...

Modify the class name of the clicked button and another button when a button is clicked in ReactJs

I have a React component that displays two buttons. When the user clicks on the left button, it should change the class of both buttons and render the ListView component. Similarly, when the user clicks on the right button, it should change the class of bo ...

Server-side WebSocket doesn't appear to be successfully transmitting messages to the frontend

Using NodeJs with Fastify on the backend in a local environment: Server side: ////// Setting up the app const fastify = require('fastify')({ logger: true }); const path = require('path'); fastify.register(require('@fastify/static& ...

Issues encountered when packaging React Native iOS application with CocoaPods

Currently, I am in the process of developing an app with the assistance of https://github.com/invertase/react-native-firebase. The recommended method for installation is through CocoaPods, but I have encountered a multitude of issues while trying to archiv ...

How to Retrieve Video Length using AJAX in the YouTube API

I have been working on a script to fetch the duration of a YouTube video using its id. Here is the code snippet I've written: var vidID = ""; var vidData; var vidDuration; function getResponse() { $.getJSON( "https://www.googleapis.c ...

Custom override of SX prop classes with Material-UI theme

I am currently working on customizing a component using the sx MUI prop. <Typography variant='h1' align='center' sx={{ fontSize: '24px', pb: '8px', fontWeight: '700' }} > ...

Angular version 11 fails to locate the lazy module

Here's a link to an application that is attempting to lazily load the BookModule using the following setup: const routes: Routes = [ { path: "", redirectTo: "/books", pathMatch: "full" }, { path: "books" ...

The divider amidst the cards zapping like electricity

Is there a way to create a vertical bar that resembles lightning? Something like this: https://i.sstatic.net/biEGb.png <div class="row d-flex justify-content-center"> <div class="col-md-3"> <div class=" ...

Converting an array of arrays to an array of objects in a React application

I have an array of arrays as follows: const arrayOfArrays = [ ['Lettuce', 60], ['Apple', 80] ]; What is the best way to transform it into an array of objects with keys for name and price, like this: const arrayOfObjects = [ {name: ...

Different language implementations of AES ECB mode yield varying outputs

I have encountered an issue while attempting to transfer an AES encrypted string from a python script to a nodejs script using ECB mode. The relevant code snippets are as follows: Firstly, I utilize pycryptodome to encrypt a string with AES: from Crypto.C ...

What is the best way to refine my selection of elements within a jQuery object?

function initializeItems($items, current, count) { $items.removeClass('z-item-current'); $items.each(function(index) { var $self = $(this); $self.data('z-item-index', index); if(index === current) { ...

Express, the mongoose package delivers a response of an empty array

I have encountered a common issue regarding pluralization with mongoose default model names. Despite trying various solutions, the problem persists as I am getting an empty array as the result. In my local mongoDB database, there are 2 documents in the "us ...

Is it possible to display a div when hovering over it and have it remain visible until

How can I make the div ".socialIconsShow" fade in when hovering over ".socialIcons", and then fade out when hovering over ".socialIconsShow"? Is there a way to keep the icons visible even after leaving ".socialIcons"? <div class="socialNetworks"> ...