</> Code Corner

JavaScript · JS HTML DOM · Lesson 49

DOM Changing CSS

element.style and classList.

The HTML DOM allows JavaScript to change the style of HTML elements, either directly with element.style or by toggling CSS classes with classList.

Example

<style>
.highlight { background: gold; padding: 10px; border-radius: 6px; }
</style>
<p id="p1">Hello World!</p>
<button onclick="document.getElementById('p1').style.color = 'blue'">Blue text</button>
<button onclick="document.getElementById('p1').classList.toggle('highlight')">Toggle highlight</button>
<button onclick="document.getElementById('p1').style.visibility = 'hidden'">Hide</button>
<button onclick="document.getElementById('p1').style.visibility = 'visible'">Show</button>
Tip: CSS property names with hyphens are written in camelCase in JavaScript: background-color becomes style.backgroundColor.

Keep reading “DOM Changing CSS”

Sign up to read the full lesson, try every example in the live editor, and take the 5-question quiz.

Chat with us 👋