# Styling Content with JavaScript
As misleading as this may seem, you can't actually style anything with JavaScript. CSS is responsible for all styling.
However, what you can do is access the style properties of any element, or you can add or remove ids or CSS classNames from any HTML element. These things are possible with JavaScript.
let main = document.querySelector("main");
main.style.padding = "10px";
main.style.margin = "1rem auto";
main.style.fontFamily = "Roboto, Arial, Helvetica, sans-serif";
2
3
4
All values for all style properties in JavaScript are set with String values.
All property names must be a single word with no hyphens. If the property name in CSS has a hyphen, then in JS it will be a camelcase name, like fontFamily
or backgroundColor
.
# ClassLists and ClassNames
If you want change the class name(s) for an element, there are two ways. First use the className
property and put whatever String value you want, including spaces and multiple class names.
The second is to use the classList
property which has three methods - add
, remove
and toggle
.
//if we start with this HTML <h1 class="maintitle">Some Title</h1>
let h1 = document.querySelector("header h1");
h1.className = "main heading shiny";
h1.classList.add("big");
h1.classList.remove("main");
//we will end up with <h1 class="heading shiny big">Some title</h1>
2
3
4
5
6
# Display and Visibility
Here are a couple reference videos about the CSS display and visibility properties, in case you are not clear on them.
To make an element appear or disappear, the recommended approach is to add or remove CSS classes via the classList
property.
However, you can directly change the display
property if you want.
let p = document.querySelector("p.first");
p.style.display = "none";
//find the first paragraph with the class "first" and hide it
p.style.display = "block";
//make the same paragraph reappear.
2
3
4
5