Building nodes in JavaScript
createElement and a fragment, so the page reflows once.
function renderSteps(steps) {
const fragment = document.createDocumentFragment();
for (const step of steps) {
const row = document.createElement("li");
row.className = "step";
row.dataset.idx = String(step.idx);
const title = document.createElement("span");
title.textContent = step.title;
const stars = document.createElement("span");
stars.textContent = "*".repeat(step.stars);
row.append(title, " ", stars);
fragment.append(row);
}
const list = document.querySelector("#steps");
list.replaceChildren(fragment);
return list.children.length;
}
How it works
- Set
textContent, notinnerHTML, for untrusted text. - A DocumentFragment batches inserts into one operation.
appendtakes several nodes or strings at once.
Keywords and builtins used here
Stringconstdocumentforfunctionofreturn
The run, in numbers
- Lines
- 22
- Characters to type
- 549
- Tokens
- 137
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 87 seconds.
Step 2 of 3 in The DOM, step 2 of 13 in The browser.