If you want to add multiple CSS styles to an element in Vanilla JS, you could do something like this:
// Grab a button element.
const button = document.querySelector('button');
button.style.backgroundColor = "red";
button.style.color = "white";
button.style.padding = "20px";
It works but looks a bit tedious and unclean. And it's hard to pass such styles around. Would be nice to put those styles in an object, like this:
const style = {
backgroundColor: "red",
color: "white",
padding: "20px"
};
Now, we need to just mix our style
object into button.style
, like this:
Object.assign(button.style, style);
And voilà, we're done!
If you find this tutorial helpful, please share it however you can :)
P.S. information for those who while reading this, sputters and tears the hair on the head, shouting: "Use CSS!". This one is not about "Why," it's about "How." Of course, you could and, in most cases, should use CSS for this, but that's another story. Relax.
Top comments (0)