How to add multiple CSS styles to an element in Vanilla JavaScript
Tim Kamanin 🚀
Posted on December 31, 2019
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.
Posted on December 31, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 29, 2024