Lesson 1 of 8
Adding elements in one go
- 13 min
- 5 checks
- 3 hints
- Go to task
Goal
Change the page once instead of a thousand times
Explanation
Every call to append on an element that's in the page can force the browser to recalculate the layout, so adding a thousand elements in a loop can mean a thousand recalculations.
A DocumentFragment is a lightweight container that lives outside the page. You build everything inside it without that cost, then add it to the page once. When you do, the container itself disappears and only the elements inside it remain.
Setting innerHTML once is also a good option, but a fragment keeps your references to the elements you created and the event listeners attached to them. innerHTML builds the elements from a string, so you're left with none of that.
Your task
Write buildList(n) so it returns a DocumentFragment holding n items, then use it to add 500 items to the list in one go.
Checks
5 checks- buildList is defined
- Returns a DocumentFragment, not an array or a string
- The fragment holds the requested number of items
- The fragment's items are li elements with text
- The list on the page has 500 items