JavaScript · Beginner level

Beginner level · Module 4: The DOM and Events · Lesson 3 of 3

Rendering Lists from Data

Keep data in an array and render the page from it, creating elements dynamically and handling events with delegation.

In this lesson you will

  • Render a list from an array of objects
  • Use event delegation for dynamically created elements

Key concepts

render functioncreateElement and appendevent delegationdata attributes

The lesson

A reliable pattern for interactive pages is: keep the data in an array, write one render() function that rebuilds the list from the data, and call render() after every change. The data is the single source of truth.

Create elements with document.createElement, set their textContent and attach them with append. Store an item's ID in a data attribute (data-id) so event handlers know which item was clicked.

Instead of adding a listener to every button, add one listener to the list and check event.target.closest("button") inside it. This event delegation also works for items added later.

Step by step

  1. Store tasks in an array of objects.
  2. Write render() that rebuilds the list.
  3. Add a task from a form and call render().
  4. Handle done and delete buttons with one delegated listener.

Practice activity

Complete the community event to-do list from the practical activity.

Expected result: Tasks can be added, marked done and removed, and the page always matches the data array.

Check your understanding

  1. What is the single source of truth in the render pattern?

    Show answer

    The data array; the page is rebuilt from it.

  2. Why use event delegation?

    Show answer

    One listener handles all items, including ones added later.

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.