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.

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Googleโ€™s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

๐Ÿ‘‹ Kindness is contagious

Please leave a โค๏ธ or a friendly comment on this post if you found it helpful!

Okay