Created a function that draws a table and passed an array to it. I specify the number of columns and rows in input, press a button and draw a table, and when I change the value in input and press again, a new table appears, but the old one is not deleted. How to write to the function delete the old table?
function createTable(tableData) { var table = document.createElement('table'); var tableBody = document.createElement('tbody'); tableData.forEach(function(rowData) { var row = document.createElement('tr'); rowData.forEach(function(cellData) { var cell = document.createElement('td'); cell.appendChild(document.createTextNode(cellData)); row.appendChild(cell); }); tableBody.appendChild(row); }); table.appendChild(tableBody); document.body.appendChild(table); } document.querySelector(".btn").addEventListener("click", function() { var row = document.querySelector(".col1").value; var col = document.querySelector(".col2").value; var row_mas = []; var col_mas = []; for (var i = 0; i < row; i++) { var col_mas = []; for (var j = 0; j < col; j++) { col_mas.push(0); } row_mas.push(col_mas); } createTable(row_mas); }); body { margin-top: 10%; margin-left: 40%; } th, td { width: 50px; border: 1px solid red; font-size: x-large; color: white; } tbody { background-color: blue; } input { width: 20px; height: 20px; } <input type="text" class="col1"> <input type="text" class="col2"> <button class="btn">Go</button>