A list built from data

Write a function that draws a list from any data it is given.

What to build

A function render(data) that makes the page match an array, and can be called again with new data.

Requirements

  • For each item, add an li to #list, with the text NAME: PRICE taka.
  • Give the cheapest item the class cheap. There is only ever one cheapest item in the data.
  • Set #summary to N items.
  • Calling render again must replace what was there.
  • Call render(items) when the page loads.

Constraints

Use createElement and textContent, not innerHTML.

Example

Pen: 10 taka

Why it works

If a single function draws the page from data, the page and the data cannot disagree. Emptying the list first is what makes the function safe to call again.

Hints

Hint 1

Inside render, empty the list first with replaceChildren().

Hint 2

Use reduce to find the cheapest item, as the lesson does.

Hint 3

render must use the data it is given, not the items variable.

Solution

Show one correct solution (try it yourself first)
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Prices</title>
  <style>
    .cheap { background: palegreen; }
  </style>
</head>
<body>
  <ul id="list"></ul>
  <p id="summary"></p>
  <script>
    const items = [
      { name: "Pen", price: 10 },
      { name: "Notebook", price: 60 },
      { name: "Ruler", price: 25 },
    ];
    const list = document.querySelector("#list");
    const summary = document.querySelector("#summary");

    function render(data) {
      list.replaceChildren();
      const cheapest = data.reduce((a, b) => (b.price < a.price ? b : a));
      for (const item of data) {
        const li = document.createElement("li");
        li.textContent = item.name + ": " + item.price + " taka";
        if (item === cheapest) li.classList.add("cheap");
        list.append(li);
      }
      summary.textContent = data.length + " items";
    }

    render(items);
  </script>
</body>
</html>

Lesson: The DOM: changing the page with JavaScript →