What is 'innerHTML vs textContent' and why is textContent the safer API for user-supplied content?
- A.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
- B.innerHTML sanitizes the string with the browser's built-in filter - removing script tags and event handlers. User input containing <img onerror=alert(1)> via innerHTML is cleaned before insertion. textContent skips the filter and writes the raw string, so user input is stored unescaped in the DOM, which makes it the riskier API
- C.innerHTML escapes the string before parsing - converting angle brackets to entities and stripping attributes. User input containing <img onerror=alert(1)> via innerHTML renders as inert text. textContent skips the escaping step and inserts the string as markup, because user input is trusted once it reaches the DOM, which is why it is considered unsafe