Variables, The DOM, & Creating Elements

shopping bag logo

The DOM

Products are currently created in the index.html with the following structure:

<article class="product-card">
  <section class="product-image">
    <img
      src="images/t-shirt-blue.png"
      alt="blue t-shirt with short sleeves"
      class="product-image"
    />
  </section>
  <section class="product-details">
    <h3>Stylish long-sleeve t-shirt in blue / medium</h3>
    <p>A stylish long sleeve blue t-shirt, in size medium.</p>
    <p class="price">$20.95</p>
  </section>
</article>

To be able to create elements using JavaScript we need a way to connect to our HTML. The DOM (Document Object Model) provides a way for JavaScript (and other languages) to do this.

The DOM represents our HTML document in a tree-like structure. At the top of the tree we have the document, followed by the html element, the head and body, then continuing to follow the structure of the elements in our document. Just like the HTML pages we created:

<!DOCTYPE html>
<html lang="en">
    <head></head>

    <body>
    <!-- html elements -->
    </body>
</html>

This document tree can be modified using JavaScript. You can find our more about the DOM here.

Creating elements

HTML elements can be created in the DOM using the createElement() method:

// script.js
document.createElement("h3");
  • document: This is the top level of the DOM tree. The document has properties and methods we can access.
  • createElement(): Is one of the methods available on the document object to create a new HTML element, our example creates an h3.

The heading also needs the text content, this is created using a method called createTextNode:

document.createTextNode('Stylish long-sleeve t-shirt in blue / medium');

Storing data into variables

Then store these into variables:

// script.js
const heading = document.createElement("h3");
const headingText = document.createTextNode('Stylish long-sleeve t-shirt in blue / medium');

A variable is a container for data. This can be an element as above, or any other data such as text or a number. A const (constant) is a type of variable when the value is not intended to be changed. For data which will be changed/updated we can use let and var.

Appending child elements

The final stage is to merge the element and text together using the appendChild method:

// script.js
const heading = document.createElement("h3");
const headingText = document.createTextNode('Stylish long-sleeve t-shirt in blue / medium');
heading.appendChild(headingText);

This has created the element but we will not yet see anything in the browser. Add the following console.log(heading);:

// script.js
const heading = document.createElement("h3");
const headingText = document.createTextNode(
    "Stylish long-sleeve t-shirt in blue / medium"
);
heading.appendChild(headingText);

// view result in the browser console
console.log(heading);

This will log the result to the console. The console is built into modern browsers to run JavaScript code and view any messages that we log.

Open up your web browser developer tools (usually right click > inspect). Then you will see a console tab to select.

The console will show the element we just created:

<h3>Stylish long-sleeve t-shirt in blue / medium</h3>

All of our elements can be created this way. Then child elements can be added to create the product structure.

Template literals (template strings)

There is also another way to create our elements:

const card = document.createElement("article");
card.classList.add("product-card");
// use backticks ``:
card.innerHTML = ``

This example creates the <article> wrapper for the product, and stores it into a variable called card.

  • The classList property will read the class attributes of an element, then we use the add() method to attach the product-card class.
  • HTML content is created using the innerHTML method.

The HTML content can be created using template literals (often called template strings). These are created using backticks (``).

Inside the <article> we will move over all of the HTML we used for the product earlier. Copy the two product <section> elements and paste between the backticks:

// script.js
const card = document.createElement("article");
card.classList.add("product-card");
card.innerHTML = `
  <section class="product-image">
    <img
      src="images/t-shirt-blue.png"
      alt="blue t-shirt with short sleeves"
      class="product-image"
    />
  </section>
  <section class="product-details">
    <h3>Stylish long-sleeve t-shirt in blue / medium</h3>
    <p>A stylish long sleeve blue t-shirt, in size medium.</p>
    <p class="price">$20.95</p>
  </section>
`

Template literals can also contain variables, and we will look at this later. The sample products can now be removed from the index.html page. Clear all of the contents from the surrounding <div> and add the id attribute:

<!-- index.html -->
<h2>All products</h2>
<!-- remove all product articles and add the id -->
<div id="product-list" class="product-grid"></div>

Selecting elements

To show the product on our page we need to do the following:

  • Select the above <div> container using JavaScript.
  • Store this into a variable.
  • Attach the product as a child of the <div> container.
// script.js

// 1. select the element and store into a variable
const productList = document.getElementById("product-list");

const card = document.createElement("article");
card.setAttribute("class", "product-card");
card.innerHTML = `<section class="product-image">
    <img
      src="images/t-shirt-blue.png"
      alt="blue t-shirt with short sleeves"
      class="product-image"
    />
  </section>
  <section class="product-details">
    <h3>Stylish long-sleeve t-shirt in blue / medium</h3>
    <p>A stylish long sleeve blue t-shirt, in size medium.</p>
    <p class="price">$20.95</p>
  </section>`;
// 2. add the product card to the wrapper
productList.appendChild(card);

Breaking it down:

  • getElementById(): is a method also available on the document object to select an element using the id (product-list).
  • const productList =: the selected element is stored into a const so we can access it.
  • productList.appendChild(card): access the variable and call the appendChild() method to add the card as a child element.

Refresh the browser to see your product on the home page.

Along with selecting an element using the ID attribute, there are also other methods available:

Selecting elements table

You can also learn more about selecting elements here.

Although the project is visually not any different than when using HTML, we have laid the foundations to repeat this structure for many products.