π― createElement() - Guided Practice (Challenge Edition!)
Welcome, code warrior π»βοΈ!
Today, you're going to build a shopping cart system using JavaScript β but instead of copy-pasting your way through, you're going to write the code with the help of clues, comments, and a few friendly hints. Let's test your skills and DOM-inate the browser! πͺ
ποΈ 1. Create a Categories Array
π§ Letβs store product types in one place so we can reuse them.
// Your code here
// Example: const categories = [...];
π 2. Display Categories Dynamically
We loop because copying and pasting HTML 10 times is a crime πͺ
function displayCategories() {
const container = document.getElementById('categories');
let html = [];
// Loop through categories and add <li> to html
// container.innerHTML = ...
}
π§ 3. Refactor with map()
β¨ Itβs like forEach() but with cooler glasses and better hygiene.
// categories.map(...).join('');
ποΈ 4. Add Products to the Cart
Because we like clicking "Add to cart" more than we like buying.
// A. Where should we store the cart products? π
// π‘ Hint: We'll need a variable (like an array) to keep track of all selected items.
// B. Define a function that takes one "product" and adds it to the cart π
// Then render the cart list so the user can see the updated items.
π 5. Display the Cart Items
Letβs actually see what weβve added.
function displayCart() {
// Select the container
// const items = cart.map(item => `<li>${item}</li>`).join('');
// Insert into the DOM
}
π§± 6. Refactor Using createElement()
Time to drop the innerHTML training wheels.
// function displayCart() {
// Clear the container
// cart.forEach(item => {
// const li = document.createElement('li');
// li.textContent = item;
// container.appendChild(li);
// });
// }
π― 7. Remove by Index
Letβs surgically remove stuff like skilled ninjas.
// function removeFromCartByIndex(index) {
// cart.splice(index, 1);
// displayCart();
// }
π§Ό 8. Remove by Name Using filter()
Because we all have a product we regret adding.
// function removeFromCartByProduct(product) {
// cart = cart.filter(item => item !== product);
// displayCart();
// }
π§ Final Boss Tip
Remember:
innerHTMLis great for fast updates.createElement()is better for long-term control and safety.map(),filter(), andsplice()are your JavaScript spells. πͺ