Changing Style
JavaScript can change the CSS style of any element by modifying its style properties. These match CSS properties, but use camelCase instead of hyphens.
Color
<p id="msg">Hello</p>
<script>
let msg = document.getElementById("msg");
msg.style.color = "red";
</script>
Background Color
msg.style.backgroundColor = "yellow";
Display (show or remove from layout)
Setting display to “none” removes the element completely.
Setting it to “block” (or other values) makes it visible again.
msg.style.display = "none"; // hides and removes msg.style.display = "block"; // shows again
Visibility (hide but keep layout space)
Unlike display, visibility keeps the element in its place but makes it invisible.
msg.style.visibility = "hidden"; // still takes space msg.style.visibility = "visible"; // show again
More Style Changes
Here are a few other simple, useful style changes:
msg.style.fontSize = "24px"; // larger text msg.style.border = "2px solid blue"; msg.style.opacity = "0.5"; // semi-transparent msg.style.textAlign = "center"; msg.style.borderRadius = "10px"; // rounded corners
Learn more style properties
Most CSS properties can be changed with JavaScript by converting their CSS name into camelCase:
background-color → backgroundColor
font-size → fontSize
See: W3Schools JavaScript Style Reference
This page was created by ChatGPT with the guidance, editorial scrutiny, and approval of the human creator of this website.