Content · Web Development · HTML

HTML DOM Security: Avoiding Unsafe innerHTML

DOM Security: Avoiding Unsafe innerHTML: The result depends on browser support and, in examples with script elements, on JavaScript being allowed. Includes a practical HTML example and an explanation.

1 views Published Oct 19, 2026 Updated Oct 19, 2026 Admin

Small interactions can make a webpage easier to use: opening a tip, changing a setting, or reusing an interface component.

What You Need to Know


Assigning untrusted strings to innerHTML can cause the browser to interpret them as code or markup. Use textContent for ordinary text, and use trusted or carefully sanitized markup only when HTML is truly needed.

In this example: insert user comments safely as text.

Try the Example


Take a look at the example. We’ll explain the important lines right below it.

<p id="user-message"></p>
<script>
    const userMessage = "<img src=x onerror=alert(1)>";
    const messageElement = document.querySelector("#user-message");
    messageElement.textContent = userMessage;
</script>

Let’s Read the Code


  • <script>: Script contains JavaScript, data, or other browser-understood script formats depending on type.
  • id: An id uniquely identifies an element on this page.

Read the named elements and attributes together. They explain how the browser connects this feature to the rest of the page.

What Happens in the Browser?


When the form reaches a server, the server must check the information again. A nice-looking HTML field is not a security control.

What makes it interactive? Look for the JavaScript that finds an element and reacts to an event. HTML provides the initial controls and content; the script updates the page. Try removing the script to see which part still works natively.

Your Turn


Run this on a local development server if it loads modules or resources. Change the visible text or trigger and check what still works with scripts disabled.

Common Beginner Mistakes


  • Assuming new HTML syntax works in every browser without testing.
  • HTML supplies structure; JavaScript is necessary for the scripted behavior in this example. Check keyboard access and focus movement too.

Key Takeaways


  • Assigning untrusted strings to innerHTML can cause the browser to interpret them as code or markup.
  • <script>: Script contains JavaScript, data, or other browser-understood script formats depending on type.
  • Treat personal information carefully. The HTML example cannot replace HTTPS, server-side security checks, or safe storage.
Share this resourceSend this page to someone who may find it useful.