Build a node tree without parsing untrusted HTML
createElement creates an element that is not yet attached to the document. Set its properties, then insert it with append or another explicit operation. Removing a node changes the current document, not an underlying database automatically.
The page shows two tasks, each with a Remove button. Titles are inserted as text, so a title containing markup characters does not become executable HTML. Activating a button removes that task's list item.
Moving versus copying
Appending an existing node moves it; one node cannot occupy two positions at once. cloneNode(true) copies a subtree's markup, but event listeners registered with addEventListener are not automatically copied. Duplicate IDs in cloned content must be addressed.
Batch construction
A DocumentFragment can hold several newly created children before insertion. It is useful for organization and batching, but should not be advertised as a universal speed guarantee. Use clear code and measure the actual large-list workload if performance matters.
Cleanup and focus
A detached node can remain in memory if another object retains a reference. Cancel associated timers or subscriptions when disposing of a widget. If the currently focused control is removed, deliberately choose a sensible next focus location for the user's task rather than leaving navigation confusing.
Practice
- Add an empty-title check before creating a task.
- Move an existing task to the end with append and observe that it is not duplicated.
- Clear only the task list with replaceChildren, avoiding unrelated page content.
- Explain why removing the displayed row does not delete a server record unless an authorized API operation also succeeds.