Changing or clearing html table with JavaScript

I am using the following code to build an html table and send it to my page:

function generateTableHead(table, data) {
    let thead = table.createTHead();
    let row = thead.insertRow();
    for (let key of data) {
      let th = document.createElement("th");
      let text = document.createTextNode(key);

function generateTable(table, data) {
    for (let element of data) {
      let row = table.insertRow();
      for (key in element) {
        let cell = row.insertCell();
        let text = document.createTextNode(element[key]);

This set of functions is called at the initial rendering of the page, and within another function which is called on every change of a dropdown menu. This is resulting in stacked tables instead of changed tables. I understand that this is due to the fact that I am appending text to an html location that already contains a table. Is there a few lines of code I can put in the beginning of the function to clears the old table before generating a new one, or am I thinking about this problem all wrong?


I lack of context here, but you can clear HTML content of an HTML element setting innerHTML to an empty sting:

const table = document.getElementById('table')
table.innerHTML = ''