JavaScript DOM Styles
A script changes an element style through the element style property. Each style is set as a string value, much like a CSS declaration.
Set a color
Setting style.color paints the element text. Reading the property back proves the value was stored.
const demo = document.getElementById("demo");
demo.style.color = "red";
console.log(demo.style.color);Set a font size
fontSize is the camelCase form of the CSS font-size name. The value keeps its px unit.
const demo = document.getElementById("demo");
demo.style.fontSize = "24px";
console.log(demo.style.fontSize);Set two styles
One element can hold several styles at once. Both values read back on one line here.
const demo = document.getElementById("demo");
demo.style.color = "blue";
demo.style.fontSize = "20px";
console.log(demo.style.color, demo.style.fontSize);Example
const demo = document.getElementById("demo");
demo.textContent = "Styled text";
demo.style.color = "green";
demo.style.fontSize = "28px";
console.log(demo.style.color);
console.log(demo.style.fontSize);Key points
- The style property holds the styles set directly on an element.
- Style property names are written in camelCase in JavaScript.
- The CSS name font-size is written fontSize in JavaScript.
- Style values are strings, so sizes keep their unit, like "24px".
- What each style property means is taught in the CSS course.
In this example, the script writes text into the demo paragraph and then sets two styles on it. Reading each style property back shows the stored values. On the page, the text appears green and larger.
Note
classList.add adds a class to an element, and the rules for that class live in CSS.
Try it Yourself
Edit the code, then press Run.
Runs in your browser โ the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
How is the CSS property font-size written in JavaScript?