Why create render()?
The previous loop appended items each time it ran. A repeatable rendering function follows a stronger rule:
Given the current data, make the relevant DOM represent that data.
In simpler words, render() is the application's display worker. You give it the current information. It updates the screen to match.
Imagine a classroom board. The state is the teacher's current list. The DOM is what is written on the board. render() erases the old list and writes the current one. Changing the teacher's list without rewriting the board does not change what students see.
const listElement = document.querySelector('#resource-list');
function render(resources) {
listElement.replaceChildren();
for (const resource of resources) {
const itemElement = document.createElement('li');
itemElement.textContent = `${resource.title} - ${resource.minutes} min`;
listElement.append(itemElement);
}
}
render(resources);
replaceChildren() removes the previous list content. The function then creates the presentation from its input. Calling render(resources) twice still shows each resource once.
Rendering is not initialization
At this point, render() does not load data, attach events or decide when the application starts. Its responsibility is narrower: synchronize a part of the DOM with provided data.
resources
|
v
render(resources)
|
v
DOM matches resources
An empty result is still a result
function render(resources) {
listElement.replaceChildren();
if (resources.length === 0) {
const message = document.createElement('p');
message.textContent = 'No resources found.';
listElement.append(message);
return;
}
for (const resource of resources) {
const itemElement = document.createElement('li');
itemElement.textContent = `${resource.title} - ${resource.minutes} min`;
listElement.append(itemElement);
}
}
An empty list does not mean that rendering failed. It may be the correct presentation of zero matching records.
Fix the bug
What is missing if a render function only appends items and can run several times? It must clear or replace the previous children before adding the current ones.
Stop and explain
Answer without code:
- What information does
render()read? - What part of the page does it change?
- Why does it remove the old list first?
If the third answer is unclear, run the version without replaceChildren() twice and observe the duplicate items.
What to remember
render() may run many times. Its job is to make the DOM agree with current data. It should not secretly load data or keep a second, conflicting copy of application state.