Changing Content and Style
Changing Content and Style with JavaScript
Once an element is selected from the DOM, JavaScript can dynamically alter its text content, inject HTML markup, manipulate CSS styles, and add/remove CSS classes to create engaging user experiences.
1. Changing Text & HTML Content
JavaScript provides three distinct properties for updating content:
| Property | Behavior | Security Risk |
|---|---|---|
textContent | Sets or returns the plain text; ignores HTML tags | 100% Safe (No XSS) |
innerText | Similar to textContent, but respects CSS visibility | Safe |
innerHTML | Parses string as HTML, inserting tags into the DOM | XSS Risk! (Caution) |
innerHTML! Malicious users can inject <script> tags or inline SVG exploit handlers. Always use textContent when displaying user input.2. Manipulating Inline CSS Styles (element.style)
You can modify CSS styles directly using the .style property. CSS properties with hyphens (background-color, font-size) are written in camelCase in JavaScript:
3. The Superior Approach: Manipulating CSS Classes with classList
Changing individual inline styles with .style leads to messy JavaScript. The professional approach is to define styled classes in CSS and toggle them using classList:
4. Manipulating Attributes: setAttribute and getAttribute
Practice Quiz
background-color written when setting styles via JavaScript (e.g. el.style....)?element.classList.toggle("active") do?classList preferred over writing individual styles with element.style?Handling Events: click, input, submit
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Selecting Elements: getElementById, querySelector | Handling Events: click, input, submit |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.