Interactive online courses HTML Academy
2026-03-09 12:23 Diff

Let’s start adding a product card. If we were to add a new element using markup, then we would add one more <li> with class product to the product list. In JavaScript, you need to take several steps to perform the same task. Let’s take it step by step.

Creating a DOM element

First, you need to create a new list element, li. We can create elements in different ways, we’ll use the createElement() method of document object. The method accepts a string with the name of the tag and returns the created DOM element. This element can be written into a variable for further manipulation:

var card = document.createElement('li');

Note that createElement is the method for the document object. That is, we use it to create an element for this document, not yet specifying where in the DOM it will be located.

Adding a class

You are already familiar with this step. Let’s work with classList of the created element:

var card = document.createElement('li'); card.classList.add('card');

Adding to the DOM-tree

The newly created element by default is not in the DOM tree and is not displayed on the page. We just store it somewhere in a variable. For a new element to appear on the page, you need to add it to the DOM. To do this, let’s find the element (parent) in the current DOM tree and insert our element into it.

We will use the appendChild() method of the parent. This method accepts the element and inserts it into the end of the parent element. That is, if there are already three elements in the list, as in our case, the element added with appendChild will become the fourth one in the list.

var list = document.querySelector('.cards'); var card = document.createElement('li'); card.classList.add('card'); // After calling this method, the new element is rendered on page list.appendChild(card);

Here’s what happens with the markup after calling appendChild:

<!-- Initial markup state --> <ul class="cards"> <li class="card">Existing element</li> </ul> <!-- State after calling appendChild --> <ul class="cards"> <li class="card">Existing element</li> <li class="card">Added element</li> </ul>

The sequence of adding an element to the DOM can be different: you can create an element using createElement, immediately insert it into the parent element, and then add classes. But this is not the best way: every change in the DOM redraws the page, and this is an expensive operation and it takes a long time.

Now create a product card, add a suitable class to it and put it at the end of the product list. Then log children in the console list to make sure that our card is in the collection of child elements. This is the standard behavior of the collection, it changes on the fly along with changing of the DOM.