Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

move first Tr to thead and replace td to th using jquery

I have a string returned from an ajax call like this

<table>
<tbody>
<tr>
<td>Name</td>
<td>Age</td>
</tr>
<tr>
<td>Ron</td>
<td>28</td>
</tr>
</tbody>
</table>

Now I want to restructure this to

<table>
<thead>
<tr>
<th>Name</th>
<th>Age</th>
</tr></thead>
<tbody>
<tr>
<td>Ron</td>
<td>28</td>
</tr>
</tbody>
</table>

How can I do this in jQuery?

The line below inserts a thead and copies the first tr into it

$(data.d).prepend("<thead></thead>").find("thead").html($(data.d).find("tr:eq(0)"))

I am trying to remove the first row in tbody after the previous line by using this line

$(data.d).find("tbody tr:eq(0)").remove()

How can I append thead,move first tr in tbody to it, replace all td inside that to th and finally remove the first tr from tbody

like image 544
Vignesh Subramanian Avatar asked Aug 31 '16 13:08

Vignesh Subramanian


2 Answers

Some step by step solution,

var jsonString = "<table><tbody><tr><td>Name</td><td>Age</td></tr><tr><td>Ron</td><td>28</td></tr></tbody></table>";
var t =$(jsonString); //jquery Table Object
var firstTR = $('tr:first',t); //geting firstTR
$('<thead></thead>')
  .prependTo(t)
  .append(
    $('td',firstTR).map(
       function(i,e){
         return $("<th>").html(e.textContent).get(0);
       }
    )
);

firstTR.remove();//removing First TR

$("#div").html(t);

//Output
console.log(t.html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div">
 
</div>
like image 167
Mujah Maskey Avatar answered Sep 22 '22 21:09

Mujah Maskey


My proposal is:

  • get the first row and for each cell create the corresponding th cell
  • prepend to table body the table header, append the header cells created
  • remove the first table body row

$(function () {
  var th = $('table tbody tr:first td').map(function(i, e) {
    return $('<th>').append(e.textContent).get(0);
  });
  $('table tbody').prepend($('<thead>').append(th)).find('tr:first').remove();
  console.log($('table').html());
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>

<table>
    <tbody>
    <tr>
        <td>Name</td>
        <td>Age</td>
    </tr>
    <tr>
        <td>Ron</td>
        <td>28</td>
    </tr>
    </tbody>
</table>
like image 41
gaetanoM Avatar answered Sep 22 '22 21:09

gaetanoM