DEV Community

Tim Kamanin πŸš€
Tim Kamanin πŸš€

Posted on β€’ Originally published at timonweb.com

4 1

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.

Top comments (0)

Jetbrains image

Build Secure, Ship Fast

Discover best practices to secure CI/CD without slowing down your pipeline.

Read more

πŸ‘‹ Kindness is contagious

If this article connected with you, consider tapping ❀️ or leaving a brief comment to share your thoughts!

Okay