Answer the question
In order to leave comments, you need to log in
How to merge rows in an HTML table using JavaScript?
Hello toaster dwellers!
Question for the JavaScript experts:
How to merge rows in an HTML table using JavaScript?
There is a table:
<table>
<tr><td>Значение 1</td><td>Количество 1</td></tr>
...
...
<tr><td>Значение 1</td><td>Количество 2</td></tr>
...
...
</table>
<table>
...
...
...
...
<tr><td>Значение 1</td><td>Количество (1+2)</td></tr>
</table>
Answer the question
In order to leave comments, you need to log in
You can play around with rows and cells and get something like this
function groupRows(table) {
var uniqueRows = {},
removedRows = [];
[].forEach.call(table.rows, function (row) {
var key = row.cells[0].textContent,
value = +row.cells[1].textContent.split(' ')[1],
sum;
if (key in uniqueRows) {
sum = uniqueRows[key].value + value;
uniqueRows[key].row.cells[1].textContent = 'Количество ' + sum;
uniqueRows[key].value = sum;
removedRows.push(row);
} else {
uniqueRows[key] = {
row: row,
value: value
};
}
});
[].forEach.call(removedRows, function (row) {
table.tBodies[0].removeChild(row);
});
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question