Sobes.tech
Senior

How to correctly insert custom text into the DOM, preserving HTML markup but avoiding XSS?

sobes.tech AI

Answer from AI

To insert custom text into the DOM while preserving HTML markup but avoiding XSS, you should:

  1. Allow only safe tags and attributes, filtering or escaping dangerous ones (e.g., <script>, inline event handlers).
  2. Use specialized libraries for HTML sanitization, such as DOMPurify.

Example using DOMPurify (JavaScript):

import DOMPurify from 'dompurify';

const userInput = '<b>Hello</b> <script>alert("XSS")</script>';
const cleanHTML = DOMPurify.sanitize(userInput);
document.getElementById('output').innerHTML = cleanHTML;

As a result, only safe HTML without malicious scripts will be inserted into the DOM.