简体   繁体   中英

How do I clear the rows in dynamically generated table?

I have a table that gets generated dynamically by fetching content from arrays stored in the localStorage .

Unfortunately, I noticed that every time the script is run, it appends to the existing table in the DOM as illustrated in the following images below:

The first time the script runs, the below is what is yielded:

在此处输入图片说明

The second time the same script is run, below is what is yielded:

在此处输入图片说明

Find below the script that generates the table above:

var array = JSON.parse(localStorage.getItem('transactionData'));
var table = document.getElementById("table");

for (var i = 0; i < array.length; i++) {
    var newRow = table.insertRow(table.length);             
    currentTransaction = array[i];

    for (var b = 0; b < keys.length; b++) {
        var cell = newRow.insertCell(b);
        cell.innerText = currentTransaction[keys[b]];

        if (keys[b] == "statusIcon") {
           console.log("keys[b] value is: " +currentTransaction[keys[b]] );
           cell.innerHTML = currentTransaction[keys[b]];
            } 
       else {
           cell.innerText = currentTransaction[keys[b]];
            }
     }
}   

This is my HTML code for the table:

<table class="table table-striped" id="table">
  <thead>
    <tr>
      <th>Status</th>
      <th>Amount</th>
      <th>Time</th>
    </tr>
  </thead>
  <tbody>
    <tr>
    </tr>
  </tbody>
</table> 

To resolve this issue, I am trying to write a script that clears the existing rendered table in DOM BEFORE running the table generating script.

Find below my script to clear the rows:

var array = JSON.parse(localStorage.getItem('transactionData'));
var table = document.getElementById("table");
var rowCount = array.length;;

for (var i = rowCount; i > 0; i--) {
    table.deleteRow(i);

}

Before the script is run, the table looks like this:

在此处输入图片说明

After this script is run I see this:

在此处输入图片说明

...and I also get the error message below:

Uncaught DOMException: Failed to execute 'deleteRow' on 'HTMLTableElement':
The index provided (5) is greater than the number of 
rows in the table (5).

Can someone kindly point out what's wrong with my script and how do I resolve this issue?

I think you should reconstruct your code. With the snippet below you can add the code when you want, or you can clear your table - when you want it. If you would like to delete single rows, then I would suggest giving them an ID (in the localStorage) and using it on the table rows.

 //var array = JSON.parse(localStorage.getItem('transactionData')); // mocking localStorage items const array = [{ status: 10, amount: 20, time: 30 }, { status: 20, amount: 30, time: 40 }, { status: 30, amount: 40, time: 50 }, { status: 40, amount: 50, time: 60 }, { status: 50, amount: 60, time: 70 } ] var tbody = document.querySelectorAll(".table tbody")[0]; // creating the table function addTableRows(arr, container) { let html = '' arr.forEach(e => html += `<tr>${createTableRow(e)}</tr>`) return html } // creating a single row (tr) of the table function createTableRow(obj) { return `<td>${obj.status}</td><td>${obj.amount}</td><td>${obj.time}</td>` } // initializing table tbody.innerHTML = addTableRows(array, tbody) // removing rows document.getElementById('removeRows').addEventListener('click', function(e) { tbody.innerHTML = '' }) // adding rows document.getElementById('addRows').addEventListener('click', function(e) { tbody.innerHTML = addTableRows(array, tbody) }) 
 <table class="table table-striped" id="table"> <thead> <tr> <th>Status</th> <th>Amount</th> <th>Time</th> </tr> </thead> <tbody> </tbody> </table> <button id="addRows">Add rows</button></br> <button id="removeRows">Remove rows</button> 

To empty the body <tbody> of the table, excluding the table <thead> . I gave the table body <tbody> a id="tableBodyContent" .

View the updated HTML code below:

<table class="table table-striped" id="table">
  <thead>
    <tr>
      <th>Status</th>
      <th>Amount</th>
      <th>Time</th>
    </tr>
  </thead>
  <tbody id="tableBodyContent">
    <tr>
    </tr>
  </tbody>
</table>

At the beginning of the dynamic table script, I run a script that reads in the value of the table body: <tbody id="tableBodyContent"> , nullifies it, and resets it with the default values.

View the updated script below:

var bodyContent = document.getElementById("tableBodyContent");
console.log("Check this out: " +bodyContent.innerHTML);
bodyContent.innerHTML = "";
bodyContent.innerHTML = "<tr> </tr>";


var array = JSON.parse(localStorage.getItem('transactionData'));
var table = document.getElementById("table");

for (var i = 0; i < array.length; i++) {
var newRow = table.insertRow(table.length);             
currentTransaction = array[i];

for (var b = 0; b < keys.length; b++) {
    var cell = newRow.insertCell(b);
    cell.innerText = currentTransaction[keys[b]];

    if (keys[b] == "statusIcon") {
       console.log("keys[b] value is: " +currentTransaction[keys[b]] );
       cell.innerHTML = currentTransaction[keys[b]];
        } 
   else {
       cell.innerText = currentTransaction[keys[b]];
        }
 }
}  

The script above console.logs :

Check this out: <tr> </tr><tr><td><i class="fas fa-check-circle colorBlue">
</i></td><td>10</td><td>10:37am, Sun</td></tr><tr><td><i class="fas fa-
exclamation-triangle colorRed"></i></td><td>50000</td><td>10:36am, Sun</td>
</tr><tr><td><i class="fas fa-exclamation-triangle colorYellow"></i></td>
<td>50000</td><td>10:35am, Sun</td></tr><tr><td><i class="fas fa-exclamation-
triangle colorYellow"></i></td><td>60000</td><td>10:33am, Sun</td></tr><tr>
<td><i class="fas fa-exclamation-triangle colorRed"></i></td><td>50</td>
<td>10:25am, Sun</td></tr><tr><td><i class="fas fa-exclamation-triangle 
colorRed"></i></td><td>6332</td><td>10:24am, Sun</td></tr>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM