DEV Community

Cover image for How to (Conveniently) add multiple CSS styles to an Element in Vanilla JS
Harsh Singh
Harsh Singh

Posted on

2 1

How to (Conveniently) add multiple CSS styles to an Element in Vanilla JS

If you want to change a single css property of an element you may do so in the following way:-

  $element.style[propertName] = newValue;
Enter fullscreen mode Exit fullscreen mode

Simple. right?

but what if you want to add multiple CSS Styles to an element??
perhaps you may use the $element.style.cssText attribute, but then your code will become really nasty and difficult to maintain.

Take a look:-

  $element.style.cssText = 'position:absolute;top:0;left:0;color:red;background:blue;padding:10px;margin:5px;';
Enter fullscreen mode Exit fullscreen mode

Now You Might Ask, "So...What's the solution to this problem??"

Since $element.style is just like any other Javascript Object we can use the Object.assign method on it too.

Like this :-

  const style = {
   position: 'absolute',
   top: 0,
   left: 0,
   color: 'red',
   background: 'blue',
   padding: '10px',
   margin: '5px'
  };

  Object.assign($element.style, style); // easy-peasy
Enter fullscreen mode Exit fullscreen mode

As you can see now the code has become more readable and maintainable.

You can go one step further and convert it into a re-usable utility function like this :-

  const style = ($el, obj) => Object.assign($el.style, obj);

  // and use it like this

  style($element, { color: 'red' });
Enter fullscreen mode Exit fullscreen mode

So That Was It. Thanks For Reading. Do Like This Post and Share It With Your Friends.

JAI HIND! JAI BHARAT!

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay