πŸ‘Ύ Web Dev
Home
  • WDIII

    • Git
    • Intro to DOM
    • Conditional Statements and Functions
    • Arrays
    • Using createElement()
    • Objects
    • Midterm
Home
  • WDIII

    • Git
    • Intro to DOM
    • Conditional Statements and Functions
    • Arrays
    • Using createElement()
    • Objects
    • Midterm
  • 🎯 createElement() - Guided Practice (Challenge Edition!)

🎯 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:

  • innerHTML is great for fast updates.
  • createElement() is better for long-term control and safety.
  • map(), filter(), and splice() are your JavaScript spells. πŸͺ„
Last Updated:
Contributors: platard, David Plata Ramirez