Start learning free

LESSON 33 OF 161 · FRONTEND: JAVASCRIPT IN THE BROWSER

Build a Card

Practice

A product card is more than one element: an li with a heading, a price and a button inside it. When the same lines build every card, put them in a function that takes the data and returns the finished element. The loop then only appends what the function hands back.

Here is a small builder for another element, a tag:

function tag(label) {
  const span = document.createElement("span");
  span.className = "tag";
  span.textContent = label;
  return span;
}
document.querySelector("footer").append(tag("New"));

An element you create lives only in memory until you append it to something on the page. append takes several elements, or text, and adds them in that order. So the heading, price and button show in the card only once they are appended to its li.

When the check opens the page, it must print eight cards like these:

text: 8 products
list
  item
    heading 3: Mug
    text: $12
    button: Add to cart
  item
    heading 3: Notebook
    text: $7 Out of stock
    button: Add to cart
  … six more items, Lamp to Gift card

Every card gets the same Add to cart button, the Notebook too: in this lesson the Out of stock badge only tells the visitor, it doesn't take the button away.

Your task: write a function productCard(product) that returns an li with the class card, holding an h3 with the product's name, a p with the class price and the text "$" followed by the price, and a button Add to cart. When the stock is 0, append a space and a span Out of stock to the price. In the loop, append to the list what the function returns.


Assignment
Follow the Coding Tutorial to write productCard, call it from the loop, then build each card's heading, price, button and badge.


Hint
Make the elements, append them to the li, and return the li at the very end of the function. Without the return, the loop gets nothing to append.


STEP 1 OF 12
    Ctrl + Enter to check