typestar

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

  1. Set textContent, not innerHTML, for untrusted text.
  2. A DocumentFragment batches inserts into one operation.
  3. append takes several nodes or strings at once.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 3 in The DOM, step 2 of 13 in The browser.

← Previous Next →