Ma6139735 Ma6139735 - 2 months ago 20
HTML Question

Merge table cells with specific class using jQuery

I'm trying to merge table cells which has the same class.



$(function () {
$('table tbody tr').each(function () {
var colspan = $(this).find('td.row').length
if (colspan > 1) {
$(this).find('td.row:first').attr('colspan', colspan)
$(this).find('td.row:not(:first)').remove()
}
})
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1">
<tbody>
<tr>
<td>text</td>
<td class="row">text</td>
<td class="row">text</td>
<td>text</td>
<td>text</td>
<td class="row">text</td>
<td class="row">text</td>
<td class="row">text</td>
</tr>
<tr>
<td>text</td>
<td>text</td>
<td>text</td>
<td>text</td>
<td>text</td>
<td>text</td>
<td>text</td>
<td>text</td>
</tr>
<tr>
<td class="row">text</td>
<td class="row">text</td>
<td>text</td>
<td>text</td>
<td>text</td>
<td>text</td>
<td>text</td>
<td>text</td>
</tr>
</tbody>
</table>





Result of above code is as bellow.



Result without merging:



Expected result:



How can I achieve this?

Answer

Try this:

$(function () {
  $('table tr').each(function () {
    let $firstRow
       ,colspan = 0
    $(this).find('td').each(function() {
      if ($(this).hasClass('row')) {
        // Save the first cell with class in $firstRow, remove the rest
        colspan === 0 ? $firstRow = $(this) : $(this).remove()
        // Count the number of cells
        colspan++
      } else if (colspan > 0) {
        // Assign the colspan and reset the counter
        $firstRow.attr('colspan', colspan)
        colspan = 0
      }
    })
    if (colspan > 0) {
      $firstRow.attr('colspan', colspan)
      colspan = 0
    }
  })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1">
  <tbody>
    <tr>
      <td>text</td>
      <td class="row">text</td>
      <td class="row">text</td>
      <td>text</td>
      <td>text</td>
      <td class="row">text</td>
      <td class="row">text</td>
      <td class="row">text</td>
    </tr>
    <tr>
      <td>text</td>
      <td>text</td>
      <td>text</td>
      <td>text</td>
      <td>text</td>
      <td>text</td>
      <td>text</td>
      <td>text</td>
    </tr>
    <tr>
      <td class="row">text</td>
      <td class="row">text</td>
      <td>text</td>
      <td>text</td>
      <td>text</td>
      <td>text</td>
      <td>text</td>
      <td>text</td>
    </tr>
  </tbody>
</table>

Comments