Apply CSS dynamically with JavaScript

Since you have also asked if there is a better way and you building a component, a better way i would recommend is for you to build such a component with frontend javascript framework because they make dynamically styles very easy out of the box take an example of Vuejs, Reactjs

`      
import React, {Component} from 'react'
import styled from 'styled-jss'
const Circle = styled('div')({
  position: 'absolute',
  width: 50,
  height: 50,
  borderRadius: '50%',
  background: (props) => (
    /* Generates a random or based on props color */
  ),
  transform: (props) => (
    /* Generates a random or based on props transform for  positioning */
  )
})
class Demo extends Component {
  componentDidMount() {
    this.tick()
  }
  tick = () => {
    requestAnimationFrame(() => {
      this.setState({/* Some new state */}, this.tick)
    })
  }
  render() {
    return (
      <div>
        {[...Array(amount)].map(() => <Circle />)}
      </div>
    )
  }
}
`

The way I would do it is to construct the CSS and set the style attribute to the proper elements. For example:

var div = document.createElement('div');
div.setAttribute("style", "color: blue, margin-top:5px");
document.body.appendChild(div);

This code will create a new div element with the style color: blue, margin-top:5px and append it to the page.


Using Vanilla JS you could do something like this.

If you want to add a CSS class named animate to an element with Id circle, do it like this.

var circle = document.getElementById("circle");
circle.classList.add('animate');

You can remove the class like this.

circle.classList.remove('animate');

Using Jquery

Use the css() function to apply style to existing elements where you pass an object containing styles :

var styles = {
  backgroundColor : "#ddd",
  fontWeight: ""
};
$("#myId").css(styles);

You can also apply one style at the time with :

$("#myId").css("border-color", "#FFFFFF");

Vanilla JS :

var myDiv = document.getElementById("#myId");
myDiv.setAttribute("style", "border-color:#FFFFFF;");

With Css :

You can also use a separate css file containing the different styles needed inside classes, and depending on the context you add or remove those classes to your elements.

in your css file you can have classes like

.myClass {
    background-color: red;
}

.myOtherClass {
    background-color: blue;
}

Again using jquery, to add or remove a class to an element, you can use

$("#myDiv").addClass('myClass');

or

$("#myDiv").removeClass('myClass');

Again, you can also do the same with vanilla JS:

document.getElementById("#myId").classList.add('myClass') 

or

document.getElementById("#myId").classList.remove('myClass') 

I think this is a cleaner way as it separates your style from your logic. But if the values of your css depends from what is returned by the server, this solution might be difficult to apply.