CSS Style Objects
Open the project folder
In our starter files, open the index.html page from this lessons folder:
07.Objects-In-More-Depth > 06.CSS-style-objects
Adding styles with JavaScript
In the DOM section we created our own HTML elements. And then we looked at how to add CSS styling to these elements using JavaScript. In the starter files we have an example of this. A simple header section with a title, and then multiple style properties applied:
<header>
  <h1>No Meat Burgers</h1>
</header>
<script>
  const header = document.querySelector('header');
  header.style.display = 'flex';
  header.style.justifyContent = 'space-between';
  header.style.padding = '0 10px';
  header.style.background = 'rgb(116, 203, 116)';
  header.style.color = 'rgb(46, 43, 43)';
</script>
This works but it is a long way of doing things, and it is not re-usable on other elements either.
Converting to an object
A solution to this is to create a style object, containing all the CSS properties and values we need:
const header = document.querySelector('header');
// 1. Comment out existing styles
// header.style.display = 'flex';
// header.style.justifyContent = 'space-between';
// header.style.padding = '0 10px';
// header.style.background = 'rgb(116, 203, 116)';
// header.style.color = 'rgb(46, 43, 43)';
// 2. create style object- camel case since it is still JavaSscript
let styles = {
  display: 'flex',
  justifyContent: 'space-between',
  padding: '0 10px',
  background: 'rgb(116, 203, 116)',
  color: 'rgb(46, 43, 43)'
}
Applying the object to elements
Now we need a way for this style object to apply to our header element, and as we recently looked at, we can use Object.assign(). This will copy all our style object properties over to our header element.
You may think at first to do this:
Object.assign(header, styles);
But, just like we did originally, we apply them to the header.style:
Object.assign(header.style, styles);
You may be a little confused at this stage as to why an object method works on an element. This is because our elements, like many things in JavaScript, are classed as objects too:
console.log(typeof header); // object
When we create new elements, we are creating element objects, and this is how we can have access to properties, methods, and events. We have already used properties, such as accessing the attributes, classList and innerHTML to name a few.
Methods we have used include querySelector and addEventListener, and these are all available on the element object.
Why not just use CSS? This is probably easier for many use cases, but this way has it’s uses too.
This was is controlled with JavaScript meaning we can change values dynamically. If we had a game, we could change a background to be red if the game was over, we could make a countdown flash faster as it is getting closer to the end, and so many more great use cases too.