Course contentsShow
← Web Development
Lesson 2903 of 2,98252. Frontend SecurityFree lesson

Safe Alternatives to Dangerous APIs

Using textContent, createTextNode, and sanitization libraries as safer alternatives.

Safe Alternatives to Dangerous APIs

You'll learn how to prevent XSS by replacing dangerous DOM manipulation methods with secure alternatives.

As you've seen, APIs like innerHTML, document.write, and eval() can execute arbitrary scripts embedded in user data. The good news? Modern JavaScript offers safer methods that treat everything as text, not code.


textContent: Text-Only Updates

Instead of innerHTML, use textContent to insert plain text. It never parses HTML tags:

// DANGEROUS
element.innerHTML = userInput; // <script>alert('XSS')</script> would execute

// SAFE
element.textContent = userInput; // displays literally as text

Think of textContent as a strict bouncer that won't let HTML through the door—only plain text allowed.


createTextNode: Building Safely

When constructing DOM nodes dynamically, use document.createTextNode():

const message = document.createElement('div');
const safeText = document.createTextNode(userInput);
message.appendChild(safeText);
document.body.appendChild(message);

This ensures user input is treated as a text node, not parsed as markup.


Sanitization Libraries: When You Need HTML

Sometimes you must accept some HTML (like formatted blog comments). Use battle-tested sanitization libraries that strip dangerous elements:

// Using DOMPurify
const clean = DOMPurify.sanitize(userHTML);
element.innerHTML = clean; // strips <script>, event handlers, etc.

These libraries act like security filters, removing anything that could execute code while preserving safe formatting.


When to Use Each

  • textContent: User-generated plain text (names, comments)
  • createTextNode: Building elements programmatically
  • Sanitization library: Rich text where some HTML is needed

Key Takeaway: Replace innerHTML and similar APIs with textContent, createTextNode, or sanitization libraries like DOMPurify to prevent XSS by treating user input as data, not executable code.