All tutorials
DOM

Change HTML and CSS with JS

Update text, attributes, classes and styles dynamically.

1. Explanation

Use textContent or innerHTML to change content, setAttribute to change attributes, element.classList (add, remove, toggle, contains) for classes, and element.style for inline CSS. Prefer classList + CSS over inline styles for maintainability.

2. Example

Try it yourself
Console
Click Run to see output.

3. Expected output

output
(no console output — modifies the element)

4. Common mistakes

  • Setting innerHTML with user input — XSS risk; use textContent
  • Forgetting to remove a class — use toggle for on/off
  • Inline styles overriding stylesheet rules unexpectedly

5. Practice questions

  1. Build a dark-mode toggle that adds/removes a 'dark' class on <body>
  2. Change an image src on hover
  3. Show/hide a div with classList.toggle('hidden')
→ Try more practice problems