Listing Orders
We continue in the same project folder throughout this section.
Lesson steps
Before we add the code to list the orders, it may be a good opportunity to give this a go yourself. If you wish to try this, here is what we are looking to do:
The Objective:
Loop through all orders and display in the browser
Steps:
- Create a function: createOrdersList().
- createOrdersList() will loop through the provided orders array.
- For each order, construct the following markup with JavaScript. Using dynamic order numbers (1,2,3...) and pizza names:
<div class="order_wrapper">
<h4>Order: 1</h4>
<ul>
<li>
1 - <span>Ham and Pineapple</span>
</li>
<li>
2 - <span>Pepperoni</span>
</li>
</ul>
</div>
- Add orders to the aside section.
This is all the steps you will need to add the orders to the aside section.
Completed code
Give this a try, if you get stuck or just want to follow along, here is the final code:
// index.js
// Add below the starter file arrays
function createOrdersList() {
orders.forEach(function (order) {
// wrapper for each order
const orderWrapper = document.createElement('div');
orderWrapper.className = 'order_wrapper';
// order number
const orderNumberEl = document.createElement('h4');
const orderNumber = document.createTextNode(`Order: ${order.id}`);
orderNumberEl.appendChild(orderNumber);
orderWrapper.appendChild(orderNumberEl);
// create pizza ul for each order:
const pizzaList = document.createElement('ul');
order.pizzas.forEach(function (pizza) {
// order quantity
const orderQuantityEl = document.createElement('span');
const quantity = document.createTextNode(`${pizza.quantity} - `);
orderQuantityEl.appendChild(quantity);
// pizza name
const pizzaNameElement = document.createElement('span');
const pizzaName = document.createTextNode(pizza.name);
pizzaNameElement.appendChild(pizzaName);
// create list item to display quantity and pizza name:
const pizzaItem = document.createElement('li');
pizzaItem.append(orderQuantityEl, pizzaNameElement);
// add items to unordered list
pizzaList.appendChild(pizzaItem);
});
// add pizza list to wrapper
orderWrapper.appendChild(pizzaList);
// add full wrapper to dom
document.querySelector('#orders').appendChild(orderWrapper);
});
}
createOrdersList();
Resulting in the three orders we have listed in the browser:
This is a long function and ideally, we want to refactor this to be smaller and more focused, and this is what we are going to do next.