matt136 matt136 - 7 months ago 8
HTML Question

Insert Additional Table Rows with jQuery

I'm attempting to insert additional table rows into a table specifically for mobile devices so that all table data cells show in a list. So for example the layout is currently 2x2 layout but I want this to show as 1x4.

The code I have below is correct for the function because I can replace

</tr><tr>
with example text and this will then show. The issue is that when I remove text and put
</tr><tr>
, it isn't taking effect and I can't see it within the source code.



jQuery(document).ready(function(){
jQuery(".desctable").find('td:nth-child(even)').append("</tr><tr>");;
});

<table class="desctable">
<tr>
<td>Table Data 1</td>
<td>Table Data 2</td>
</tr>
<tr>
<td>Table Data 3</td>
<td>Table Data 4</td>
</tr>
</table>





So basically I need the front-end result to be this:



<table class="desctable">
<tr>
<td>Table Data 1</td>
</tr>
<tr>
<td>Table Data 2</td>
</tr>
<tr>
<td>Table Data 3</td>
</tr>
<tr>
<td>Table Data 4</td>
</tr>
</table>





Could anybody please advise why this isn't working? Thank you very much for any help you can offer.

Answer

jQuery's append() method can only insert elements or text nodes into the DOM. </tr><tr> is not an element or a text node.

Instead, you could insert a row after each existing row, using append() to move the last cell of the previous row to the new row:

$('.desctable tr').each(function() {
  $('<tr>')                          //Create new row.
    .append($(this).find('td:last')) //Add the last cell of the current row to it.
    .insertAfter($(this));           //Place it after the current row.
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="desctable">
  <tr>
    <td>Table Data 1</td>
    <td>Table Data 2</td>
  </tr>
  <tr>
    <td>Table Data 3</td>
    <td>Table Data 4</td>
  </tr>
</table>

Comments