Is it at all possible to dynamically style elements using CSS properties that are stored within a JS object?
For example, changing both the width
and background
of a simple <div>
element:
<div id="box"></div>
<button id="btn">click me</button>
The box is initally styled with:
div {
background: grey;
width: 100px;
height: 100px;
}
The box will be restyled when clicking the button element as so:
btn.addEventListener('click', () => {
// Code to change box style here...
}
I have seen the use of setAttribute('style', 'some style stuff here');
, however I have come to understand that this will simply replace ALL of the style attribute associated with the element, rather than appending/changing the properties defined within :-(
My goal here is to do hold CSS properties in a JS object such as:
const myStyle = {
'background': 'green',
'width': '20px'
}
and apply this to the element.
I know this can be done by holding the properties in another CSS class named something like '.box-transform' and then adding that to the classList of the element... But I am wanting to do this through JS.
My initial attempt was something along the lines of:
btn.addEventListener('click', () => {
for (let [key, val] of Object.entries(myStyle)) {
console.log(`${key}: ${val}`)
box.setAttribute('style', `${key}: ${val}`)
}
});
However I was running into the issue of the overriding nature 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>