Start learning free

LESSON 32 OF 161 · FRONTEND: JAVASCRIPT IN THE BROWSER

Build Elements in JavaScript

Practice

So far the product cards were written by hand in index.html. A real shop builds its page from data: the script reads the products and makes one element for each.

Three moves build an element. document.createElement("li") makes a new element, which exists only in memory. You set its textContent and its className (the property is className because class is a reserved word in JavaScript). Then parent.append(element) puts it on the page, as the parent's last child.

const footer = document.querySelector("footer");
const line = document.createElement("p");
line.textContent = "Closed on Sundays";
line.className = "small";
footer.append(line);   // the footer gets a second paragraph

Now index.html has an empty list, <ul id="products" class="products"></ul>, and data.js has the array PRODUCTS with the eight products. The lines below your loop count the elements with the class card. When the check opens the page, it must print:

> open the page
  console.log: app.js is running
  screen:
    header
      heading 1: Corner Shop: open today
    main
      heading 2: Our products
      text: 8 products
      list
        item: Mug $12
        item: Notebook $7
        item: Lamp $29
        item: Pen $2
        item: Plant $15
        item: Teapot $22
        item: Stapler $9
        item: Gift card $50
      aside
        text: Free delivery on orders over $30
    footer
      text: Corner Shop, 12 Market Street. Open 9:00 to 18:00.

Your task: under the heading lines of app.js, find the empty list, then loop over PRODUCTS. For each product, make an li, set its text to the name, " $" and the price, give it the class card, and append it to the list.


Assignment
Follow the Coding Tutorial to build the product list from PRODUCTS: one new li per product, with its text and its class, appended to ul#products.


Hint
Everything that happens once per product goes inside the loop's braces. The count lines come after the loop, so each item must get the class card inside the loop.


STEP 1 OF 6
    Ctrl + Enter to check

    Dom Create Elements in JavaScript

    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free