How to add multiple CSS styles to an element in Vanilla JavaScript

timonweb

Tim Kamanin 🚀

Posted on December 31, 2019

How to add multiple CSS styles to an element in Vanilla JavaScript

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";
Enter fullscreen mode Exit fullscreen mode

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"
};
Enter fullscreen mode Exit fullscreen mode

Now, we need to just mix our style object into button.style, like this:

Object.assign(button.style, style);
Enter fullscreen mode Exit fullscreen mode

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.

đź’– đź’Ş đź™… đźš©
timonweb
Tim Kamanin 🚀

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