What is 'innerHTML vs textContent' and why is textContent the safer API for user-supplied content?
- A.innerHTML and textContent are equivalent; the browser renders them the same way
- B.innerHTML parses the string as HTML - creating DOM nodes and interpreting event handlers. User input containing <img onerror=alert(1)> via innerHTML executes JavaScript. textContent treats the entire string as text, no HTML parsing - user input is rendered literally as text, preventing XSS
- C.textContent is less efficient than innerHTML and should only be used for small amounts of text
- D.innerHTML is safe for user input if the input is UTF-8 encoded; encoding prevents XSS
Why B is correct
DOM API safety: element.textContent = userInput - always safe, userInput is treated as plain text. Tags are displayed literally as < > & etc. element.innerHTML = userInput - dangerous if userInput contains HTML; tags are parsed, events registered, URLs in href/src are loaded. element.innerText = userInput - similar to textContent but triggers layout reflow (slower). createTextNode(userInput) + appendChild is the most explicit safe approach. Best practice: default to textContent for all text rendering; use innerHTML only when you intentionally need HTML, and always sanitize with DOMPurify + Trusted Types in those cases.
Know someone studying for Web App Fundamentals? Send them this one.