CodeRatchet CodeRatchet - 3 months ago 15
HTML Question

loop through table tr and retrieve value from second td

I have the following HTML table:

<table id="review-total">
<tbody><tr class="wlp">
<td class="left-cell">WLP Total</td>
<tr class="tax">
<td class="left-cell">GST</td>
<tr class="net">
<td class="left-cell">Order Total</td>
<td class="net-price">$218.90</td>

I'm trying to loop through this table and retrieve the values i.e

199.00, 19.90 and $218.90 I have the following code:

var reviewTotal = document.getElementById('review-total');
for (var i = 1; i < reviewTotal.rows.length; i++) {
if (reviewTotal.rows[i].cells.length) {
wlpTotal = (reviewTotal.rows[i].cells[1].textContent.trim());
gstAmount = (reviewTotal.rows[i].cells[3].textContent.trim());
totalOrderAmount = (reviewTotal.rows[i].cells[5].textContent.trim());

I'm having a small issue trying to retrieve those values specified above, at present the error I get is textContent is undefined.

Can someone show me how I should go about retrieving those values, unfortunately I'm not strong in Javascript.


You have 3 rows and each row has only 2 cells. The 3 and 5 indices are undefined and undefined doesn't have .textContent property.

If you want to store the values by using specific variable names, you remove the loop and select the target elements manually:

var wlpTotal = reviewTotal.rows[0].cells[1].textContent.trim();
var gstAmount = reviewTotal.rows[1].cells[1].textContent.trim();
var totalOrderAmount = reviewTotal.rows[2].cells[1].textContent.trim();

If you want to store the values in an array, you can code:

var values = [], function(row) {
   return row.cells[1].textContent.trim();

By using ES2015's Destructuring Assignment you can also extract the array's elements:

var [wlpTotal, gstAmount, totalOrderAmount] = values;