JavaScript - Changing HTML & CSS
Overview
Estimated time: 15–20 minutes
JavaScript can change HTML content and CSS styles dynamically, enabling interactive and responsive web pages.
Learning Objectives
- Change text, HTML, and attributes of elements.
- Modify CSS styles using JavaScript.
Prerequisites
Changing Content
el.textContent = 'New text';
el.innerHTML = 'Bold';
Changing Styles
el.style.backgroundColor = 'yellow';
el.classList.toggle('hidden');
Common Pitfalls
- innerHTML can introduce security risks (XSS) if used with untrusted content.
Summary
Use JavaScript to update content and styles for dynamic, interactive web pages. Prefer textContent over innerHTML for plain text.