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

Jul 22, 2019 · Updated: Jul 23, 2019 · by Tim Kamanin

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'); = "red"; = "white"; = "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, like this:

Object.assign(, 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.

Hey, if you've found this useful, please share the post to help other folks find it:

There's even more:

Subscribe for updates

  • via Twitter: @timonweb
  • old school RSS:
  • or evergreen email ↓ ↓ ↓