Skip to curriculum
Jump to the editor

17.5. Insert, move and replace nodes with fragments and templates

Medium
Topics
20–35 min

A to-do list, a chat log and a search result page all keep a list in the page in step with data: render it, add a few items in the middle, move one when the user drags it, replace one when it is edited. Doing that well means three habits: build items from a <template> instead of HTML strings, add many nodes in one insertion, and move existing nodes instead of rebuilding them, so a checked box or a listener on them survives.

Write five helpers in list.js.

Files

  • list.js: the helpers below.
  • index.html (read-only): a sample list and its template, to try the helpers in the page:
HTML
<template id="todo-item">
  <li class="item">
    <input type="checkbox" class="item-done">
    <span class="item-text"></span>
  </li>
</template>

An item is { id, text, done }. Its element is a clone of the template's element, with data-id set to the id, the text in .item-text, and .item-done checked when done is true. An item of a list is a direct child of the list, found by its data-id.

JAVASCRIPT
createItem(template, item)                // returns a new element
renderItems(list, template, items)        // replaces the list's children
insertItems(list, template, items, index) // inserts new items at index
moveItem(list, id, beforeId)              // returns true, or false when an id is unknown
replaceItem(list, template, item)         // returns the old element, or null

Requirements

  1. createItem returns a new element cloned from the template's element (the template's content may have whitespace around it), with data-id (as a string), the text and the checkbox set. It is not in the page yet.
  2. The text is set as text: markup in it is shown, never parsed.
  3. The template itself never changes, and every call gives a new element.
  4. renderItems replaces every child node of the list (text included) with the new items, in order. An empty array empties the list.
  5. renderItems and insertItems add all their items in one insertion: a MutationObserver on the list sees one record that adds nodes.
  6. insertItems puts the first new item at position index among the list's elements. 0 is the start; a missing index, or one past the end, means the end.
  7. moveItem moves the same element (not a copy) just before the item with beforeId, or to the end when beforeId is null or undefined. Its checked state and listeners survive. Moving an item before itself changes nothing.
  8. moveItem returns true when the ids were found, and false with no change when either id is not an item of the list.
  9. replaceItem puts a new element for item where the item with item.id was, and returns the old element (no longer in the page). It returns null and changes nothing when there is no such item.
  10. Ids are compared as strings and may contain any characters, quotes and brackets included. Items of a nested list inside an item do not count.

Examples

JAVASCRIPT
const list = document.getElementById("todo");
const template = document.getElementById("todo-item");

renderItems(list, template, [
  { id: 1, text: "Plan", done: true },
  { id: 2, text: "Build" },
  { id: 3, text: "Ship" },
]);
// data-ids: 1 2 3

insertItems(list, template, [{ id: 4, text: "Test" }], 2);
// data-ids: 1 2 4 3
JAVASCRIPT
moveItem(list, 1, null);  // true; data-ids: 2 4 3 1, and item 1 is still checked
moveItem(list, 9, 2);     // false; nothing changes
JAVASCRIPT
replaceItem(list, template, { id: 4, text: "Test again" }); // the old <li data-id="4">
replaceItem(list, template, { id: 99, text: "?" });         // null

Environment

  • Plain JavaScript in a browser page; the tests call the global functions with lists and templates they build.
  • Any DOM methods are allowed. innerHTML with item text is not safe, and the tests check for it.
  • Keyed diffing (updating a list to match new data with the fewest moves) is out of scope.

Hints

  1. A DocumentFragment is not part of the page. What happens to its children when you insert it?
  2. What does insertBefore do with a node that is already in the page?

The explanation comes with the course

A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.

  • Every line explained
  • The mistakes each test catches
  • Links to the lessons behind it
Back to the question
Loading the editor…