Creating HTML Elements: First, we have to learn how to create new HTML elements. The method document.createElement() creates the HTML element specified by the passed name. In this case, we are creating a li element, an HTML element representing an item of a list.
const element = document.createElement('li')
Attaching HTML Elements: Then, we need a method to attach the newly created element to the DOM (or to other elements). To this end, we will use the method node.appendChild(element), which attaches an element (“element“) as a child of another element (“node“).
- Create a container element
- Loop through the list items
- Render each item into an HTML Element
- Attach an HTML Element into the container Element
- Attach container element to the DOM
Let’s create two functions, renderItem and renderList that implement the algorithm outlined before.
We now can call the renderList function with document.body and our data to render the list.
renderList(document.body, ['Item 1', 'Item 2', 'Item 3']);
Output: Following will be the output of the above example.