Problem Statement
Explain different ways to manipulate the DOM. Compare innerHTML, textContent, createElement, and when to use each.
Explanation
JavaScript provides multiple methods for DOM manipulation, each with different use cases, performance, and security implications.
InnerHTML:
Gets or sets HTML content as a string. Parses HTML and creates elements. Fast for large replacements. Security risk with user input due to XSS attacks. Use for trusted HTML content or templates. Avoid for user-generated content.
TextContent:
Gets or sets text content without HTML parsing. Faster and safer than innerHTML. Includes hidden text. Use for plain text to prevent XSS. Best for user input display. No security concerns.
InnerText:
Gets visible text respecting CSS display. Triggers reflow, slower than textContent. Excludes hidden elements. Use when you need only visible text. Less common in practice.
CreateElement with appendChild:
Creates elements programmatically. Most secure and flexible. Better performance for single elements. Full control over attributes and properties. Use for dynamic element creation. Best for complex structures.
InsertAdjacentHTML:
Inserts HTML at specific position. Does not replace existing content. More efficient than innerHTML for additions. Same XSS risk as innerHTML. Use for adding content without replacing.
Document Fragment:
Creates off-screen container for multiple elements. Add many elements, then append once. Minimizes reflows and repaints. Best performance for bulk operations. Use when adding many elements.
When to use each:
Use textContent for user-generated text. Use createElement for programmatic element creation. Use innerHTML only for trusted HTML templates. Use document fragments for multiple elements. Always sanitize user input.
Performance considerations:
TextContent is fastest for text. InnerHTML is fast for bulk replacements. CreateElement is best for single elements. Document fragments optimize multiple additions.
Security best practices:
Never use innerHTML with user input. Always escape or sanitize user data. Prefer textContent or createElement. Use Content Security Policy. Validate on server side too.