Web Development Pro | Lesson 028 | Render Lists with Real Elements
Web Development Pro · Lesson 28 of 60
Module 3: JavaScript foundations
In this lesson
Prerequisites and learning outcomes
Complete lesson 27 first. This lesson builds on dom creation, fragments, and empty states. By the end, you can render a data-driven workshop list with safe text and stable structure. Plan 10–15 minutes for the core explanation and additional time for the worked practice.
Render records without turning strings into markup
The directory now stores workshop records as JavaScript objects. To display them, create actual elements and assign their text. This makes the relationship between data and structure explicit: a record becomes a list item containing a heading and a category sentence. The data is not treated as executable HTML.
A renderer should define what happens for both ordinary and empty input. If there are no matching workshops, a blank list alone is ambiguous: perhaps loading failed, perhaps the data is empty, or perhaps the page broke. Show a clear empty-state message and an accurate count so the visitor understands the current result.
Build a small rendering function
The complete page supplies an empty ul, a status paragraph, and a hidden empty-state paragraph. The renderer owns the list's children but not the search controls or main heading. This ownership boundary matters because replacing a larger region could discard focused controls or listeners that other code still needs.
const workshops = [
{ id: 'bike-101', title: 'Bicycle basics', category: 'Repair' },
{ id: 'sew-101', title: 'Mending clothes', category: 'Textiles' }
];
const list = document.querySelector('#workshops');
const count = document.querySelector('#result-count');
const empty = document.querySelector('#empty-message');
if (!list || !count || !empty) throw new Error('Workshop list elements missing.');
function renderWorkshops(items) {
const fragment = document.createDocumentFragment();
for (const item of items) {
const row = document.createElement('li');
row.dataset.id = item.id;
const heading = document.createElement('h2');
heading.textContent = item.title;
const category = document.createElement('p');
category.textContent = `Category: ${item.category}`;
row.append(heading, category);
fragment.append(row);
}
list.replaceChildren(fragment);
count.textContent = `${items.length} workshop results.`;
empty.hidden = items.length !== 0;
}
renderWorkshops(workshops);
A DocumentFragment is a temporary container whose children can be inserted together. Appending it moves its children into the destination; the fragment itself does not become a visible wrapper element. This is a convenient construction pattern, not a guarantee that every use will be faster than every alternative. Measure performance when it matters.
Keep content and behavior separate
TextContent handles the title and category as literal text. Even a title containing <script> characters remains a text value in this renderer. That prevents this particular HTML-injection path. It does not prove every other part of the application is secure; a later URL field would need a URL-specific policy before being used in a link.
The record id goes into a data attribute for stable identification. It is not automatically an HTML id, and it does not grant access to anything. If two records accidentally have the same internal id, later selection logic can become ambiguous even though the browser permits matching data attributes. Data validation will address uniqueness explicitly in later lessons.
The renderer uses h2 because each workshop is a major item below the page's h1. If the same component is embedded under a different heading structure, its heading level may need adjustment. Reusable rendering should respect its document context rather than hardcoding a visual font size as a semantic choice.
Replace deliberately rather than append forever
ReplaceChildren removes the old result nodes before inserting the new ones. If the renderer only appended every time, repeating a search could duplicate the entire list. A useful invariant is that the visible list represents exactly the items passed to the latest render call, with no leftovers from earlier calls.
Full replacement is simple for this small static result list, but it has tradeoffs. Focused controls inside replaced rows can disappear, and per-row listeners attached to old nodes are not transferred to new ones. A more interactive list may need stable keyed updates or delegation from a persistent container. Do not introduce those complexities before the interface needs them, but know what the simple strategy assumes.
Keep the controls outside the replaced region. Updating results should not erase the search field or move the visitor's cursor unexpectedly. The count can be a polite status message, while the whole list need not become an aggressively announced live region. Short meaningful updates are usually easier to follow than a complete repeated page reading.
Define empty-state behavior precisely
When items is empty, the fragment has no children, the list becomes empty, the count says zero results, and the hidden property becomes false on the empty message. The message is present in the HTML from the start so its wording can be reviewed with the rest of the page. Its visibility follows the current result state.
This example sets the hidden property to the booleans true or false. The platform also supports the distinct until-found state, which this example does not use. Writing hidden="false" in HTML would still hide an element because the attribute is present. Setting empty.hidden = false in JavaScript correctly removes that hidden state. This is another example of why properties and serialized attributes cannot always be treated identically.
Verify the renderer's contract
The runtime tests check two records, an empty array, a subsequent rerender, and a markup-like title. They confirm row count, text, data ids, and empty-state visibility in a limited DOM double. They also verify that rendering twice does not duplicate rows. Static checks confirm the page supplies the required containers.
These tests do not establish visual layout, browser focus effects, or screen-reader announcements. Use a real browser to inspect the resulting headings, list semantics, and status experience. The renderer is only one part of the visitor's journey, so its correct output should be tested again when search controls are added.
Worked practice
Worked exercise 1: Stop duplicate results
Task: Every search appends matching rows, so old results remain. Worked answer: replace the owned list children with the new fragment. The latest result set should completely determine the list contents. Test a two-result search followed by a one-result search to expose leftovers.
Worked exercise 2: Show no matches clearly
Task: A filter returns an empty array. Worked answer: render zero rows, update the count to zero, and reveal the empty-state paragraph. Do not leave the previous results visible while claiming the new search succeeded.
Worked exercise 3: Protect a literal title
Task: A title contains “<b>Repair</b> basics.” Worked answer: assign it through textContent so the characters appear as text. The renderer should not let data decide which elements are created; structure remains under the implementation's control.
Knowledge check
Question 1
What happens when a DocumentFragment is appended? A) Its children move into the destination. B) It becomes an extra visible div. C) The fragment and its children are cloned into the destination. D) Its children remain in the fragment after insertion.
Check question 1: answer and explanation
Answer: A. The fragment is a temporary container, not a rendered wrapper.
Question 2
Why use replaceChildren in this renderer? A) To preserve every old row. B) To make the list match the latest items exactly. C) To keep detached listeners automatically. D) To validate record ids.
Check question 2: answer and explanation
Answer: B. Replacement avoids accumulating stale or duplicated results.
Question 3
What does empty.hidden = false do? A) Adds hidden="false" as an active hiding attribute. B) Removes the paragraph node from the document. C) Clears the hidden state. D) Clears the paragraph text as well as its hidden state.
Check question 3: answer and explanation
Answer: C. The boolean property is set to false, unlike merely writing the string false in markup.
Question 4
What is a tradeoff of replacing interactive rows? A) Every listener on the unchanged list container is removed too. B) Replacement automatically preserves the focused row identity. C) Listeners on old rows are transferred to matching new rows. D) Focus and listeners on removed nodes can be lost.
Check question 4: answer and explanation
Answer: D. Replacing nodes removes their identity and attached state from the current tree.
Question 5
Which claim is supported by the provided tests? A) The modeled renderer replaces rows and handles empty input correctly. B) All screen readers announced the count. C) Every viewport layout passed. D) Browser focus never moves.
Check question 5: answer and explanation
Answer: A. The fixture tests defined DOM operations without simulating the complete browser.