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.
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.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:
classListChanging individual inline styles with .style leads to messy JavaScript. The professional approach is to define styled classes in CSS and toggle them using classList:
setAttribute and getAttributebackground-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?Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| Selecting Elements: getElementById, querySelector | Handling Events: click, input, submit |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.
Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.