CodeBlanks Logo Icon CodeBlanks

innerHTML risks

JavaScript course · Expert · Lesson 26/63

Learn how innerHTML creates an XSS risk and safer alternatives.

The risk of innerHTML

innerHTML interprets the string you assign as HTML. If that string comes from the user, the tags and scripts inside it run. This is the most common XSS door.

For example, when you write el.innerHTML = userInput, any <script> tag inside userInput is processed as code by the browser. Stay away from innerHTML unless the data is trusted.

textContent is safe

textContent writes the value you assign as plain text, not as HTML. Tags and entities are not interpreted; the browser displays them as-is.

So el.textContent = userInput never treats the input as a tag, whatever it contains. When you write user-supplied text to an element, textContent should always be the first choice.

Exercise Create a badge

Write a function createBadge, parameter label. Create a badge element with document.createElement('span'). Assign label to badge.textContent and return badge.

Show example solution
First define the function, then create the span element, assign label to textContent, finally return badge.
Example solution:
function createBadge(label) {
  const badge = document.createElement('span');
  badge.textContent = label;
  return badge;
}

Test yourself

  1. Which is a safe DOM update method?

    • element.textContent = userInput
    • element.innerHTML = userInput
    • element.outerHTML = userInput
    • document.write(userInput)
    Show answer

    element.textContent = userInput — Correct! textContent writes the value as plain text and prevents XSS.

  2. Safe assignment with textContent

    const el = document.getElementById('msg');
    el.____ = 'Welcome';
    Show answer
    const el = document.getElementById('msg');
    el.textContent = 'Welcome';
  3. Match the DOM properties

    textContent
    writes as text
    innerHTML
    interprets as HTML
    outerHTML
    replaces the tag
    innerText
    gives visible text

All lessons in Expert