Cell Merger

Use Case

Maybe you want to merge adjacent table cells with the same contents. You could probably just use rowspan, but maybe you can't for some reason. Maybe you can use this Javascript instead. It doesn't do colspan merges, because that would be a horrible mess to include.


Put this in the head section. It only does the first column. You can easily loop through the rest of the columns, changing the number in cells[0]:

window.onload = function() { // Automatically run when the page is loaded.
	var table = document.getElementById('mytable'); // Get the table using its id. Could use getElementByClassName() instead, if there's more than one table.
	var counter_row = 0;
	while(row = table.rows[counter_row]) { // Look through the rows.
		var rowspan = 0;
		while(table.rows[counter_row + rowspan] && row.cells[0].innerHTML == table.rows[counter_row + rowspan].cells[0].innerHTML) {
			This is where the magic happens.
			For each row, look at the following cells in the same column.
			If they have the same contents, we'll remove them from the DOM.
			if(rowspan) {
				table.rows[counter_row + rowspan].cells[0].remove();
		row.cells[0].setAttribute('rowspan', rowspan); // Increase the rowspan with the number of merged cells.
		counter_row += rowspan; // Skip the rows we just merged with in the loop.

Privacy Policy.