17.5. Insert, move and replace nodes with fragments and templates
Topics
This question is in
17. DOM: changing the page and eventsA 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:
<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.
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 nullRequirements
createItemreturns a new element cloned from the template's element (the template's content may have whitespace around it), withdata-id(as a string), the text and the checkbox set. It is not in the page yet.- The text is set as text: markup in it is shown, never parsed.
- The template itself never changes, and every call gives a new element.
renderItemsreplaces every child node of the list (text included) with the new items, in order. An empty array empties the list.renderItemsandinsertItemsadd all their items in one insertion: aMutationObserveron the list sees one record that adds nodes.insertItemsputs the first new item at positionindexamong the list's elements.0is the start; a missingindex, or one past the end, means the end.moveItemmoves the same element (not a copy) just before the item withbeforeId, or to the end whenbeforeIdisnullorundefined. Its checked state and listeners survive. Moving an item before itself changes nothing.moveItemreturnstruewhen the ids were found, andfalsewith no change when either id is not an item of the list.replaceItemputs a new element foritemwhere the item withitem.idwas, and returns the old element (no longer in the page). It returnsnulland changes nothing when there is no such item.- 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
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 3moveItem(list, 1, null); // true; data-ids: 2 4 3 1, and item 1 is still checked
moveItem(list, 9, 2); // false; nothing changesreplaceItem(list, template, { id: 4, text: "Test again" }); // the old <li data-id="4">
replaceItem(list, template, { id: 99, text: "?" }); // nullEnvironment
- Plain JavaScript in a browser page; the tests call the global functions with lists and templates they build.
- Any DOM methods are allowed.
innerHTMLwith 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
- A
DocumentFragmentis not part of the page. What happens to its children when you insert it? - What does
insertBeforedo 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