styfle styfle - 20 days ago 6
Javascript Question

Destructuring assignment to assign styles to a DOM element

JavaScript has a nifty Destructuring assignment short hand feature that works well when creating multiple variables from properties in an object.

I want to do something similar with the styles for a button element. Here is my working code:

var button = document.createElement('button');
button.style.background = '#30a900';
button.style.color = 'white';
button.style.border = '1px solid white';


I want to do something like the following:

var mystyles = {
background: '#30a900',
color: 'white',
border: '1px solid white',
};
var button = document.createElement('button');
button.style = mystyles;


However, this doesn't work as expected. Is there a feature of ES6 to do this assignment?

Answer

What about Object.assign?

var button = document.createElement('button');
button.innerText = 'Object.assign';
var mystyles = {
    background: '#30a900',
    color: 'white',
    border: '1px solid white',
};
Object.assign(button.style, mystyles);
document.body.appendChild(button);