# Adding a new purchase in a shopping calculator

First, let's make it so that when the button is clicked, a new row with a purchase is added to the table:

`add.addEventListener('click', function() { let tr = document.createElement('tr'); let td; td = document.createElement('td'); td.textContent = name.value; td.classList.add('name'); tr.appendChild(td); td = document.createElement('td'); td.textContent = price.value; td.classList.add('price'); tr.appendChild(td); td = document.createElement('td'); td.textContent = amount.value; td.classList.add('amount'); tr.appendChild(td); td = document.createElement('td'); td.textContent = price.value * amount.value; td.classList.add('cost'); tr.appendChild(td); td = document.createElement('td'); td.textContent = 'remove'; td.classList.add('remove'); tr.appendChild(td); table.appendChild(tr); });`

The solution I provided, however, has obvious problems with code duplication: in fact, for each cell we write the same code.

It would be appropriate to have some function to create a table cell. Let this function accept a reference to a row of the table as the first parameter, the second parameter is the text of the table cell, and the third is the name of the CSS class of the cell:

`function createCell(tr, value, name) { }`

With such a function, we could rewrite the above code as follows:

`add.addEventListener('click', function() { let tr = document.createElement('tr'); createCell(tr, name.value, 'name'); createCell(tr, price.value, 'price'); createCell(tr, amount.value, 'amount'); createCell(tr, price.value * amount.value, 'cost'); createCell(tr, 'remove', 'remove'); table.appendChild(tr); });`

Implement the function `createCell` I described.

Copy my code to add a new purchase. Test adding a new purchase to the table.

Modify the `createCell` function so that it returns the created table cell via `return`.

← →
↑
en ru