DEV Community

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

Posted on

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!

Top comments (0)