Update the CSS styles using properties specified within an object

Is it possible to dynamically apply CSS styles stored in a JavaScript object to elements?

For instance, can we change the width and background of a basic <div> element:

<div id="box"></div>
<button id="btn">click me</button>

The initial style of the box is set as:

div {
  background: grey;
  width: 100px;
  height: 100px;
}

We want to restyle the box when clicking the button:

btn.addEventListener('click', () => {
  // Code to adjust box style here...
}

I have tried using

setAttribute('style', 'some style stuff here');
, but this method replaces all existing style attributes instead of updating specific properties.

My objective is to define CSS properties in a JS object like this:

const myStyle = {
  'background': 'green',
  'width': '20px'
}

and then apply these styles to the element.

While I know it's possible to achieve this by creating a separate CSS class (.box-transform) and adding it via classList, I am looking for a solution that uses JavaScript directly.

My initial approach looked something like this:

btn.addEventListener('click', () => {
  for (let [key, val] of Object.entries(myStyle)) {
    console.log(`${key}: ${val}`)
  box.setAttribute('style', `${key}: ${val}`)
}
});

However, I faced issues with the overriding behavior of setAttribute...

const btn = document.getElementById('btn');
const box = document.getElementById('b');

const myobj = {
  'width': '20px',
  'background': 'yellow'
};

btn.addEventListener('click', () => {
  for (let [key, val] of Object.entries(myobj)) {
    console.log(`${key}: ${val}`)
  box.setAttribute('style', `${key}: ${val}`)
}
});
.box {
  width: 300px;
  height: 300px;
  background: grey;
}
<div class="box" id="b"></div>
<button id="btn">click</button>

Answer №1

const button = document.getElementById('button1');
const section = document.getElementById('section');

const myStyles = {
  'width': '150px',
  'background-color': 'green'
};

button.addEventListener('click', () => {
  for (let [property, value] of Object.entries(myStyles)) {
    section.style[property] = value;
  }
});
.section {
  width: 200px;
  height: 200px;
  background-color: lightblue;
}
<div class="section" id="section"></div>
<button id="button1">Click Here</button>

Answer №2

To start, create the CSS as a string and then utilize the cssText property:

const btn = document.getElementById('btn');
const box = document.getElementById('b');

const myStyles = {
  'width': '20px',
  'background': 'yellow'
};

btn.addEventListener('click', () => {
  var cssText = '';
  for (let [key, val] of Object.entries(myStyles)) {
    cssText += `${key}: ${val};`  
  }
  box.style.cssText = cssText;
});
.box {
  width: 300px;
  height: 300px;
  background: grey;
}
<div class="box" id="b"></div>
<button id="btn">click</button>

You can also change the style using the key-value pairs in the object within the loop:

const btn = document.getElementById('btn');
const box = document.getElementById('b');

const myStyles = {
  'width': '20px',
  'background': 'yellow'
};

btn.addEventListener('click', () => {
  for (let [key, val] of Object.entries(myStyles)) {
    box.style[key] = val;  
  }
});
.box {
  width: 300px;
  height: 300px;
  background: grey;
}
<div class="box" id="b"></div>
<button id="btn">click</button>

Answer №3

Discover multiple ways in which we can implement styles from a JavaScript object to an element's style attribute.

For a concise syntax, especially when ES6 is accepted, we can utilize Object.assign:

Object.assign(elem.style, stylesObject);

We can also transform the styles object into an array using Object.entries, then apply map to convert each key-value pair to a suitable string and eventually combine them using join:

elem.style = Object.entries(stylesObject).map(x => `${x[0]}:${x[1]}`).join(';');

An alternative approach involves concatenating a string with different for loops.

We have the option of using for in:

let str = '';
for (let style in stylesObject) {
    str += `${style}:${stylesObject[style]};`;
}
elem.style = str;

or utilizing forEach:

let str = '';
Object.entries(stylesObject).forEach(style => {
    str += `${style[0]}:${style[1]};`;
})
elem.style = str;

or making use of for of:

let str = '';
for (let style of Object.entries(stylesObject)) {
    str += `${style[0]}:${style[1]};`;
}
elem.style = str;

Lastly, we can opt for a classic for loop:

const stylesArray = Object.entries(stylesObject);
let str = '';
for (let x = 0; x < stylesArray.length; x++) {
    str += `${stylesArray[x][0]}:${stylesArray[x][1]};`;
}
elem.style = str;

You can explore this benchmark I created to observe the performance impact of these methods.

[If you're interested, take a look at version 2 of the benchmark, where additional variations are included (mainly switching from Object.entries to Object.keys).]

I decided not to include the option of applying the style in each loop iteration instead of concatenation due to its significant performance drawback, as evidenced by the results in the benchmarks.

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

What is the process of exporting ES6 from main.js in Vue.js 2.0?

I've encountered an issue while using the webpack-simple-2.0 template for Vue.js (version 2.0.0-beta.5). When I include export const FOO='bar' in my main.js file, I'm unable to successfully import { FOO } in another .js file - it alway ...

Combine a string and integer in JavaScript without using quotation marks between them

Is there a way to concatenate a string and an integer in JavaScript without getting the ": Here is the code snippet: "<agm-map latitude=" + response.latitude + " longitude=" + response.longitude + "></agm-map>"; What it currently results in: ...

PHP implementation for a static header layout

I am interested in learning how to update content without refreshing the header. I have created a simple example below. Header.php <html> <head> </head> <body> <ul> <li><a href="index.php" ...

Utilize React to dynamically load diverse data arrays into a slick slider component

I am currently working on a component that includes a slider displaying photos linked to different rooms. The next step is to move this slider to a separate page or component, which will display content for rooms, news, and promotions using different arr ...

"Although disabled, input elements can still be focused on in Firefox browser

Illustrative example let userInput = document.createElement("input"); userInput.id = "user-input"; userInput.type = "number"; userInput.className = "user-number-input"; userInput.disabled = true; document.body.appendChild(userInput); .number-inp ...

Tips for customizing the appearance of an HTML5 progress bar using JQuery

Here is my method for obtaining the bar: let bar = $('#progressbar'); Styling and animating it is no problem, using either of these methods: bar.css(...) bar.animate(...) However, I am wondering how to adjust the CSS specifically for the prog ...

Tips for preserving data while attempting to access the schema

Attempting to store data from a book that includes author and genre information, referenced in separate files. The issue arises when making the reference in the main schema. Although the book carries details of the book itself, it fails to establish refer ...

Error in Laravel npm package

Working on my Laravel project, I encountered an issue while trying to implement a video chat feature using https://github.com/PHPJunior/laravel-video-chat?ref=madewithlaravel.com with laravel-echo-server. Despite trying various solutions, none seemed to wo ...

Incorporate PHP functionality into an HTML document

I'm looking to incorporate a PHP code into my phoneGap application (HTML). I've attempted the following code, but unfortunately it's not functioning as expected. <html> <head> <title>PHP Integrated with HTML&l ...

How can I add scrolling functionality to the active list item with React?

I created a music player that allows users to search for songs by artist. Check out the CODE SANDBOX here! Take a look at how the SongsList component is structured in my project: const SongsList = (props) => { const { loading, errorMess ...

sending numerous ajax requests and they all seem to be returning identical results

When firing multiple ajax requests using the setinterval() function, I noticed that both requests are bringing back the same information from another page. Here is the JavaScript code: function views() { setInterval(function(){var xmllhttp //alert ...

Retrieving Information from Ajax Call Using Python

I am struggling to figure out how to retrieve data from an Ajax request in my JavaScript code within a Python Flask application. The Ajax request I am working with does not involve jQuery. I have attempted using request.form.get() and request.get_json() i ...

Maintain scroll position during ajax request

I am working on a single-page website that contains numerous containers. Each container's content is loaded dynamically via ajax, so they may not all be populated at the same time. These containers have variable heights set to auto. The website uti ...

Is it true that Internet Explorer does not support border radius?

Styling with CSS border-bottom: 1px solid silver; background-color: #000; background: rgb(51,51,51); /* Old browsers */ background: -moz-linear-gradient(top, rgba(51,51,51,1) 0%, rgba(153,153,153,1) 100%); /* FF3.6+ */ background: -webkit-gradient(linear, ...

What is the method for calling a function in a JavaScript file?

I am facing a challenge with reinitializing a JavaScript file named AppForm.js after a successful ajax post response. Within the file, there are various components: (function(namespace, $) { "use strict"; var AppForm = function() { // Cr ...

Generate a new Div dynamically, positioned higher than the rest

Once a second, this script will utilize AJAX to open a new page and display the contents in a dynamically created div on this page. However, the issue is that the new divs are stacking under each other, and I would prefer them to be added at the top instea ...

Dealing with Memory Issues in Google Apps Scripts

Currently, I am addressing a challenge within my organization that requires me to maintain some level of ambiguity. However, I have been granted permission to discuss this issue openly. The task at hand involves creating a script to analyze a Google Sheet ...

Updating a global variable in Angular after making an HTTP call

I'm facing a challenge where I have a global variable that needs to be updated after an HTTP GET call. Once updated, I then need to pass this updated variable to another function. I'm struggling to figure out the best approach for achieving this. ...

Using array.map with Promise.all allows for concurrent execution

Currently, I am working with an array of images and attempting to apply image processing techniques using an asynchronous function. The code is functioning as expected since each image in the array contains an index field representing its position. // Res ...

Retrieving information from an Angular service using a specified function

I have been working on accessing data from a method within a service that returns coordinates, which are used to make HTTP requests in my application. I have integrated my Leaflet code into the controller to be able to access the lat,lng coordinates for ...