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>