You build an HTML code generator by separating three concerns: a schema that describes what users can add, a state model that stores their choices, and a rendering layer that converts state into HTML. The generator never asks users to type markup; it composes strings or nodes from validated inputs. The key condition is that all user-supplied text passes through an escaping function before it reaches output, or the tool becomes a cross-site scripting vector the moment anyone pastes it into a page.
That architecture works whether you are building a drag-and-drop page builder, a form-to-email-template tool, a snippet maker for a docs site, or a table generator for a CMS. The steps below go from a blank file to a working generator, then cover escaping, testing, extension, and the failure modes that bite real projects.
Start by fixing the scope and the output contract
Before writing code, decide what the generator produces and how strict that output must be. There are three common output contracts, and they change the whole design:
Fragment mode produces a snippet you paste into an existing page (a table, a card, a form). You control only the fragment's internal markup. Document mode produces a complete page with doctype, head, and body. You own everything, including metadata. Template mode produces markup that gets inserted into someone else's engine, which may strip tags, rewrite attributes, or have its own escaping rules. Email HTML is the classic example.
Write the contract down as a short spec: which elements the generator supports, which attributes it exposes, what it does with raw text, and what characters it refuses to emit. A generator with a written output contract is testable; one without it drifts into "it seems to work."
A reasonable minimum scope for a first version is roughly a dozen element types: headings, paragraphs, links, images, lists, blockquotes, code blocks, tables, horizontal rules, containers, buttons, and form fields. That covers most practical use cases and still fits in a few hundred lines of code.
Model the document as data, not as markup
The single most important decision is to store the document as a plain data structure and render it in one place. Users edit the tree; the renderer walks the tree. Never let UI handlers concatenate HTML strings directly, or every UI change becomes an opportunity to produce invalid markup.
A minimal node model looks like this:
Text nodes are separate from element nodes on purpose. If text lives inside attributes or as a special "raw" string, escaping becomes conditional and eventually wrong. Keeping text as its own node type means the renderer has exactly one place where text gets escaped.
For a more structured generator, add element-specific data: an image node stores src, alt, width, and height; a list node stores an ordered/unordered flag plus item children; a table node stores rows of cells. The renderer converts these to tags. The UI edits the fields. Neither side knows the other's internals.
Store the tree in a single state object and make every mutation go through a small set of functions: insertNode, removeNode, moveNode, updateAttrs, updateText. This gives you undo/redo almost for free (snapshot the tree or record operations) and makes the generator's behavior reproducible, which matters when users report bugs.
Build the escaping and sanitization layer first
The rendering layer must distinguish text content from attribute values, because the escaping rules differ slightly and the contexts are not interchangeable.
For text content, escape at minimum &, <, and >. Practically, also escape " and ' so the same function can be reused in quoted attribute contexts without a second code path. The order matters: replace & first, then the others, or you double-escape ampersands.
For attribute values, the same five characters are sufficient when the attribute is always quoted with a consistent quote character. That is why the renderer should always emit quoted attributes, never unquoted ones. Unquoted attributes have a much larger set of forbidden characters and are a regular source of bugs.
Two trapdoors need explicit handling:
URL-bearing attributes. href and src accept javascript: and data: URLs in most browsers. Allowlist schemes: http, https, mailto, tel, and relative URLs. Reject anything else, or replace it with an empty string and surface a warning. Raw HTML. If you offer a "raw HTML" node for advanced users, mark it clearly in the model, skip escaping for that node only, and warn in the UI. Every generator that adds raw HTML eventually ships a stored-XSS bug, so make the decision deliberately rather than by accident.
Sanitization is a related but separate problem. If the generator imports existing HTML (say, user-pasted snippets) and re-emits it, you need an HTML parser plus an allowlist-based sanitizer rather than a hand-rolled regex. Use a maintained library in your language's ecosystem for that; do not attempt to write a sanitizer from scratch.
Write the renderer as a single pure function
The renderer takes the tree and returns a string (or a DOM fragment). It should be pure: same input, same output, no network calls, no reading global state. This makes it trivially testable and lets you render on the server, in a worker, or in a test harness without a browser.
Pseudocode for the core walk:
Add four practical rules:
1: Void elements (img, br, hr, input, meta, link) never get a closing tag. Maintain a small set and check membership. 2: Always quote attributes and skip attributes whose value is null or undefined rather than emitting attr="". 3: Emit attributes in stable order (sort keys). Stable output makes diffs, caching, and tests far easier. 4: Pretty-print optionally. A separate formatting pass can add indentation, but keep the renderer itself whitespace-minimal so that inline elements like a and strong don't get broken onto new lines inside text.
For document mode, wrap the result in a fixed skeleton: doctype, , head with charset, viewport, title, and any user-provided meta, then body. The skeleton itself should be a constant your code controls, not something the user can reshape into malformed markup.
If you render to DOM nodes instead of strings, you get browser-level escaping for free via textContent and setAttribute. Many builders use the DOM path for the editor preview and the string path only for the final export. Building both from the same tree model keeps them consistent.
Design the state layer and the UI that edits it
A generator becomes a product when the UI maps cleanly to the model. The standard layout is three panels: a palette or toolbar on the left, the edited tree in the center (as a preview and/or an outline), and a property inspector on the right.
The property inspector is where most of the complexity lives. When a user selects a node, the inspector shows the fields relevant to that node type, populated from the node's attrs and text. Editing a field calls updateAttrs or updateText. Because the preview re-renders from the tree after every mutation, there is no synchronization code to get wrong.
Keep the preview honest. Render it inside a sandboxed container if you support raw HTML, or render it with the exact same escaping as the export so users see what they will get. A preview that escapes differently from the exporter is a classic source of "it looked fine in the editor" bugs.
Add these state-layer behaviors early because they are painful to retrofit:
Undo/redo. Operation log or tree snapshots, capped at a reasonable depth. Selection identity. Every node gets an ID so selection survives re-renders. Never key selection by array index. Validation state. Each field can have an error string; the export button is disabled or shows warnings when errors exist. Import/export of the state itself. Saving the tree as JSON lets users resume and gives you test fixtures. Version the JSON schema with a version number field from day one.
Validate input before rendering, not after
Validation happens in the editor and in the renderer, and they serve different purposes. The editor validation gives users useful messages. The renderer validation is a last line of defense that never lets unsafe output through even if a caller skips the editor.
Practical checks:
Required attributes. An image without alt is an accessibility problem; a link without href is a dead link. Warn in the UI and either omit or default in the renderer. URL scheme allowlist as described above, with an empty string or a warning on rejection. Attribute names. If you allow arbitrary attributes, validate the name against a conservative pattern (letters, digits, hyphens, underscores, data- prefixed) to prevent attribute-splitting tricks with spaces or quotes. Tag allowlist. The renderer should refuse any tag not in the generator's supported set. This prevents a buggy UI or an imported tree from injecting , "onmouseover="x, and & to check double-escaping. Attribute values containing quotes to try to break out of the attribute. URLs of the form javascript:alert(1), JavaScript:alert(1), and data:text/html,.... Attribute names with spaces or quotes to try to inject extra attributes. A node tree that includes an unsupported tag to confirm the renderer rejects it.
Include one check that the escaping order is right: a literal & followed by lt; should render as <, not as <.
For the UI layer, a handful of end-to-end tests that click through adding, reordering, and editing nodes will catch wiring regressions without making you write a test for every button.
Extend the generator without forking the renderer
The most common way generators rot is that every new element type adds a new branch in the renderer and a new conditional in the property inspector. Keep both declarative instead.
Define each supported element in a registry, with its tag, allowed attributes (name, type, required, default), whether it is void, and the fields the inspector should show. The renderer reads from the registry to know what tags exist. The inspector generates its form from the attribute definitions. Adding a new element type becomes a registry entry, not a code change in multiple places.
This pattern pays off for the "template" use case (prebuilt assemblies of nodes) and for presets like a complete card or a form-with-submit. Each preset is just a tree; inserting it calls the same insertNode used by the palette.
For the export path, add these features in roughly this order of payoff: copy to clipboard, download as an .html file, and save the tree JSON alongside the HTML. If your users need framework output (JSX, a template literal), write that as a second renderer that consumes the same tree. Sharing the tree model across renderers is what keeps a generator maintainable as output targets multiply.
A worked estimate: a small team building a fragment generator with about a dozen element types, escaping, validation, undo/redo, and golden tests can reasonably plan on a few days of work for the core (model, renderer, escaping, tests) and a week or two for the editor UI and inspector. Add time for security review if any untrusted input is involved. The renderer and escaping layer are small; the UI and validation are where the effort actually goes.
Common failure modes and how to avoid them
Most broken generators fail in one of four ways.
Escaping drifted between preview and export. The preview used DOM APIs and the export used string concatenation, and only one of them escaped correctly. Fix: one tree, one renderer, and tests that compare preview and export output for the same tree.
Raw HTML crept in without a warning. A "paste HTML" feature was added for convenience and the output is now trusted. Fix: model raw HTML as an explicit node type, label it in the UI, keep it behind a toggle, and never let it appear in output generated from untrusted sources without sanitization.
Selection broke on reorder. Selection was keyed by index, so moving a node selected a different one. Fix: stable IDs assigned at creation.
Unsupported tags sneaked through the tag field. The UI only offered a dropdown, but import of saved JSON introduced unsupported tags. Fix: the renderer's tag allowlist, enforced at render time, and a validation pass on import.
There is a fifth, subtler failure: the generator emits valid-looking HTML that is semantically wrong for its context. A inside a , a inside a , or a outside a list will parse, but browsers will rearrange it in ways your users did not intend. If your generator composes arbitrary nesting, add a small structure rules table that the editor enforces (for example, block elements only in block or container parents) and let the renderer reject invalid trees with a clear error rather than emitting markup the browser will silently fix.
Once the core works, the highest-value additions are usually an import path (paste HTML, parse, map into the tree), accessibility defaults (empty alt flagged, headings in order, labels attached to inputs), and a summary view that shows the generated HTML with syntax highlighting. All three build on the same model and renderer rather than adding parallel code paths, which is the test of whether the architecture was right.