Using Javascript To Mergetwo Html Rows
Solution 1:
This is some very messy code, in the end, but what you're trying to do here is quite a bit more complicated than it seems, and I'm afraid I don't have time to give a well coded answer.
What we're essentially doing here is going through each row of the table, and checking it against the previous row. If the first cells of each row are equal, then we'll merge them.
Merging them is slightly complicated, as we need to be able to filter out those cells which contain 'PARADA', else they'll simply overwrite the cells without 'PARADA' from the previous row.
This is all slightly hacky, and could be done better. You could, for instance, split this out into smaller functions, or create the new cell objects containing 'PARADA' properly, rather than just a fake element with only the textContent
property.
That being said, I believe this will work for you:
constgetMergedRow = (rowOne, rowTwo) => {
const noParadaOne = _.mapValues(rowOne.cells, x =>
x.innerHTML.indexOf('PARADA') === -1 ? x : null)
const noParadaTwo = _.mapValues(rowTwo.cells, x =>
x.innerHTML.indexOf('PARADA') === -1 ? x : null)
return _.mapValues(noParadaOne, (x, i) => {
return x ? x : (noParadaTwo[i] ? noParadaTwo[i] : {textContent: 'PARADA'})
})
};
constmergeRows = tableElement => {
const rows = tableElement.rows;
let previousLabel = undefined;
let previousRow = undefined;
for (let i = 0; i < rows.length; i++) {
const x = rows[i];
const rowLabel = x.cells[0].innerHTML;
if (rowLabel === previousLabel) {
const newRow = getMergedRow(x, previousRow);
tableElement.deleteRow(i);
tableElement.deleteRow(i-1);
const insertedRow = tableElement.insertRow(i-1);
Object.values(newRow)
.forEach((cell, i) => {
const newCell = insertedRow.insertCell();
const newText = document.createTextNode(cell.textContent)
newCell.append(newText)
})
i--;
}
previousLabel = rowLabel;
previousRow = x;
}
}
mergeRows(document.getElementById('t'))
body {
font-family: arial;
}
td {
padding: 10px;
}
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script><tableid='t'><tr><td></td><td>GL1</td><td>GL1</td><td>GL3</td></tr><tr><td>08.00</td><td>PARADA</td><td>PARADA</td><td><ahref="#">PARADA</a></td></tr><tr><td>09.00</td><td><ahref="#">VEGAS14INTEL</a></td><td>PARADA</td><td>PARADA</td></tr><tr><td>09.00</td><td>PARADA</td><td>LOCIL14</td><td>PARADA</td></tr><tr><td>10.00</td><td>PARADA</td><td>PARADA</td><td>PARADA</td></tr><tr><td>10.00</td><td>PARADA</td><td>Test</td><td>PARADA</td></tr><tr><td>10.00</td><td>Another test</td><td>Test</td><td>PARADA</td></tr><tr><td>11.00</td><td>x</td><td>y</td><td>z</td></tr></table>
Post a Comment for "Using Javascript To Mergetwo Html Rows"