How do I iterate through table rows and cells in JavaScript?
If you want to go through each row(<tr>
), knowing/identifying the row(<tr>
), and iterate through each column(<td>
) of each row(<tr>
), then this is the way to go.
var table = document.getElementById("mytab1");
for (var i = 0, row; row = table.rows[i]; i++) {
//iterate through rows
//rows would be accessed using the "row" variable assigned in the for loop
for (var j = 0, col; col = row.cells[j]; j++) {
//iterate through columns
//columns would be accessed using the "col" variable assigned in the for loop
}
}
If you just want to go through the cells(<td>
), ignoring which row you're on, then this is the way to go.
var table = document.getElementById("mytab1");
for (var i = 0, cell; cell = table.cells[i]; i++) {
//iterate through cells
//cells would be accessed using the "cell" variable assigned in the for loop
}
How do I iterate through table rows and cells in JavaScript and add the values?
Below code will add first and second td/th
and show sum in third td/th
.
Note : You can further add error handling of Nan and other things.
Jquery Code :
$('table.tg tr').each(function() {
var third_var = parseInt($(this).find('th:first-child, td:first-child').html()) + parseInt($(this).find('th:nth-child(2), td:nth-child(2)').html());
$(this).find('th:nth-child(3), td:nth-child(3)').html(third_var);
});
Javascript Code : Online Demo As requested by @Alex_89
var table = document.getElementsByClassName("tg");
var t = table[0];
for (var r = 0; r < t.rows.length; r++) {
t.rows[r].cells[2].innerHTML = parseInt(t.rows[r].cells[0].innerHTML) + parseInt(t.rows[r].cells[1].innerHTML);
}
Loop Through Table and add values in JavaScript
You can do it by
var table = document.getElementById('table');
for (var r = 0, n = table.rows.length; r < n; r++) {
for (var c = 0, m = table.rows[r].cells.length; c < m; c++) {
var image = document.createElement("img");
if(table.rows[r].cells[c].innerHTML === "Up"){
image.src = "/your_image_path_for_up";
} else {
image.src = "/your_image_path_for_down";
}
var newCell = row.insertCell(c+1);
newCell.appendChild(image);
}
}
This will append a new cell with an image to the right of your cell with "Up" or "Down".
How to iterate through this html table and get data from rows whose last col is not empty?
In your script, as one of several possible modifications, how about the following modification?
From:
var tableData = [];
var table = document.getElementById("dtable");
console.log(table)
for (var i = 0; i < table.length; i++) {
let tableCells = table.rows.item(i).cells;
let cellLength = tableCells.length;
for (let j = 0; j < cellLength; j++) {
let cellVal = tableCells.item(j).innerHTML;
tableData.push(cellVal)
}
}
console.log(tableData)
To:
var table = document.getElementById("dtable");
console.log(table)
var [, ...tr] = table.querySelectorAll("tr");
var tableData = [...tr].map(r => {
var td = r.querySelectorAll("td");
return [...td].map((c, j) => j != 3 ? c.innerHTML : c.querySelectorAll("select")[0].value);
});
console.log(tableData)
- In this modification, from a table, the table rows are retrieved. And, the table cells are retrieved from the table rows. In teh case of the dropdown list, the value is retrieved from the dropdown list.
Note:
- When this modification was not the direct solution to your issue, I think that when you provide your whole script, it will help to correctly understand your question.
Iterate through html table and calculates value
In addition to the markup cleanup/sanitize task(s) one could implement kind of a micro-component approach.
A viable solution which also is agnostic to (decoupled from) a certain DOM hierarchy can be based on custom data attributes and dataset
access together with bound handler data ...
function jsonParse(value) {
let result = null;
try {
result = JSON.parse(value);
} catch(exception) {}
return result;
}
function sanitizeFloatValue(value) {
value = parseFloat(value);
return Number.isFinite(value) ? value : null;
}
function updateTotalValueFromBoundContextData(/* evt */) {
const { source, target, baseValue, toFixed } = this;
const totalValue = baseValue * (sanitizeFloatValue(source.value) || 0);
target.value = (typeof toFixed === 'number')
? totalValue.toFixed(toFixed)
: totalValue;
}
function initializeUpdateTotalValue(componentRoot) {
const source = componentRoot
.querySelector('[data-base-value]');
const target = componentRoot
.querySelector('[data-total-value]');
const baseValue = sanitizeFloatValue(source.dataset.baseValue) || 0;
const config = jsonParse(componentRoot.dataset.updateTotalValue) ?? {};
const toFixed = sanitizeFloatValue(config.toFixed);
const context = { source, target, baseValue, toFixed };
source
.addEventListener('input',
updateTotalValueFromBoundContextData.bind(context)
);
// initial update call
updateTotalValueFromBoundContextData.call(context);
}
function main() {
document
.querySelectorAll('[data-update-total-value]')
.forEach(initializeUpdateTotalValue);
}
main();
body { zoom: .8; }
tr, td { margin: 0!important; padding: 0!important; height: unset!important; }
<form name="product-orders">
<!-- <script src="calculation.js"></script> //-->
<table class="u-table-entity">
<colgroup>
<col width="20%">
<col width="2.1%">
<col width="22%">
<col width="21.7%">
<col width="34.2%">
</colgroup>
<tbody class="u-table-alt-grey-5 u-table-body">
<tr style="height: 55px;">
<td class="u-table-cell u-table-cell-1"><b>Produkt</b><span style="font-weight: 700;"></span>
</td>
<td class="u-table-cell"></td>
<td class="u-table-cell u-table-cell-3"><b>Einzelpreis</b></td>
<td class="u-table-cell u-table-cell-4"><b>Menge</b></td>
<td class="u-table-cell u-table-cell-5"><b>Gesamtpreis</b></td>
</tr>
<tr style="height: 55px;" data-update-total-value='{"toFixed": 2}'>
<td class="u-table-cell">Kornspitz</td>
<td class="u-table-cell"></td>
<td class="u-table-cell">
<p value="1.39">1,39 €</p>
</td>
<td class="u-table-cell">
<input type="number"
min="0" value="0" step="1"
name="quantity-Kornspitz"
id="quantity-Kornspitz"
data-base-value="1.39"
/>
</td>
<td class="u-table-cell">
<p>
<output for="quantity-Kornspitz" data-total-value>0</output>
€
</p>
</td>
</tr>
<tr style="height: 55px;" data-update-total-value='{"toFixed": 2}'>
<td class="u-table-cell">Row 2</td>
<td class="u-table-cell"></td>
<td class="u-table-cell">
<p value="5.39">5,39 €</p>
</td>
<td class="u-table-cell">
<input type="number"
min="0" value="0" step="1"
name="quantity-Row_2"
id="quantity-Row_2"
data-base-value="5.39"
/>
</td>
<td class="u-table-cell">
<p>
<output for="quantity-Row_2" data-total-value>0</output>
€
</p>
</td>
</tr>
<tr style="height: 55px;" data-update-total-value>
<td class="u-table-cell">float number calculation</td>
<td class="u-table-cell"></td>
<td class="u-table-cell">
<p value="1.39">1,39 €</p>
</td>
<td class="u-table-cell">
<input type="number"
min="0" value="5" step="1"
name="quantity-Row_3"
id="quantity-Row_3"
data-base-value="1.39"
/>
</td>
<td class="u-table-cell">
<p>
<output for="quantity-Row_3" data-total-value>0</output>
€
</p>
</td>
</tr>
<tr style="height: 55px;" data-update-total-value='{"toFixed": 4}'>
<td class="u-table-cell"><code>toFixed</code> set to 4</td>
<td class="u-table-cell"></td>
<td class="u-table-cell">
<p value="5.39">5,39 €</p>
</td>
<td class="u-table-cell">
<input type="number"
min="0" value="3" step="1"
name="quantity-Row_4"
id="quantity-Row_4"
data-base-value="5.39"
/>
</td>
<td class="u-table-cell">
<p>
<output for="quantity-Row_4" data-total-value>0</output>
€
</p>
</td>
</tr>
</tbody>
</table>
</form>
Iterate through selective cells in a table row JavaScript / jQuery
You can use the cell's index like this :
var table = $('tr[id^="row"]')
var tabCells = {0: "name", 2: "size", 4: "quantity", 5: "price"} //These are the names of the needed cells
var tabRows = []; //This will store the rows data
table.each(function(){
var tabRow = {}; //This will store the current row data
$.each(this.cells, function(index){
if($.inArray(index, [0,2,4,5]) > -1)
tabRow[tabCells[index]] = $(this).text();
//e.g: tabRow[tabCells[0]] => tabRow["name"]
})
tabRows.push(tabRow);
})
How to iterate through a table rows and get the cell values using jQuery
$(this)
instead of $this
$("tr.item").each(function() {
var quantity1 = $(this).find("input.name").val(),
quantity2 = $(this).find("input.id").val();
});
Proof_1
Proof_2
javascript to loop through table rows with a classname
What you have is a good first effort for being new to JavaScript, but, yes, there are quite a few items that need updating. :)
Here is what you would need to do what you are trying to do:
function checkForm() {
var rows = document.getElementsByClassName("item-row");
var arr = new Array();
for (i = 0; i < rows.length; i++) {
var cols = rows[i].getElementsByTagName("td");
for (j = 0; j < cols.length; j++) {
arr.push(cols[j].textContent);
}
}
}
You need to cycle through each row . . . the easiest way to do this by going from
i = 0
toi < rows.length
in your for loop.Once you have a row, you need to gather all of the columns in the row, by finding all of the
<td>
elements (var cols = rows[i].getElementsByTagName("td");
);Then, you loop through each of those, just like you did with the rows (
j = 0
toj < cols.length
Finally, to get the text contained in each
td
, you use thetextContent
property . . . values (i.e., thevalue
property) are used only for<input>
elements
There were a couple of syntax errors in there, too (you used ,
instead of ;
, when building your for
loop and you used val
instead of value
, when attempting to get the td
content), but that was all that I saw.
Edit: I'm also assuming that you just did not paste your <table>
tags in when you added your HTML, but, if you didn't your <tr>
tags must be inside a <table
.
Edit 2: My solution also skips the looking at the tags inside the <td>
elements, since they are not standard (4 contain <textarea>
inputs and the 5th a <span>
). If you want to go down one more level of detail, you could use .value
on the textareas and (again) .textContent
on the <span>
. By using .textContent
one level up, you are ignoring all HTML tags insid the <td>
tags and returning only the text.
Related Topics
Using "Object.Create" Instead of "New"
How to Sort 2 Dimensional Array by Column Value
How to Send a Variable Number of Arguments to a JavaScript Function
How to Add New Array Elements at the Beginning of an Array in JavaScript
How to Render Components with Different Layouts/Elements Using React-Router-Dom V6
Preserving a Reference to "This" in JavaScript Prototype Functions
Defining Methods via Prototype VS Using This in the Constructor - Really a Performance Difference
Dynamically Add Script Tag with Src That May Include Document.Write
Remove Objects from Array by Object Property
How to Open a Bootstrap Modal Window Using Jquery
Determining Image File Size + Dimensions via JavaScript
What Values Can a Constructor Return to Avoid Returning This
Jquery's Jquery-1.10.2.Min.Map Is Triggering a 404 (Not Found)
Browsers, Time Zones, Chrome 67 Error (Historic Timezone Changes)
Is There a Better Way to Do Optional Function Parameters in JavaScript
Javascript: How to Join/Combine Two Arrays to Concatenate into One Array