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

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

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>

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>

A much simpler solution:
t = $('table#tbl2')
firstTr = t.find('tr:first').remove()
firstTr.find('td').contents().unwrap().wrap('<th>')
t.prepend($('<thead></thead>').append(firstTr))
table thead tr th {
background: green;
}
table tbody tr td {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="tbl1"><tbody><tr><td>Name</td><td>Age</td></tr><tr><td>Ron</td><td>28</td></tr></tbody></table>
<br /><br />
<table id="tbl2"><tbody><tr><td>Name</td><td>Age</td></tr><tr><td>Ron</td><td>28</td></tr></tbody></table>
Here is the explanation of the code:
Remove the first tr element from the dom.
Find the td elements, take their contents() and unwrap the td.
Wrap each of the contents() of the td with th tag.
Add the <thead> tag to table and append the tr we worked on to the thead

You can make:
$('table').prepend('<thead></thead>'); // Add thead
$('table tr:eq(0)').prependTo('table thead'); // move first tr to thead
$('table thead').html(function(id, html) { // you might use callback to set html in jquery
return html.replace(/td>/g, 'th>'); // replace td by th
// use regExp to replace all
});
When you use .prependTo, this move the element to another in top and you might use callback in .html function in jquery.
Reference:
http://api.jquery.com/prependto/
http://api.jquery.com/appendto/

Years passed (so no jQuery anymore), and I want to do this and have solved it like this. The idea is 1) get the first row(<tr>), 2) replace every <td> tags on the first row to <th>.
const txt = `<table>
<tbody>
<tr>
<td>Name</td>
<td>Age</td>
</tr>
<tr>
<td>Ron</td>
<td>28</td>
</tr>
</tbody>
</table>`;
const el = document.createElement('table');
el.innerHTML = txt;
[...el.querySelector('tr').querySelectorAll('td')].forEach(td =>
td.outerHTML = td.outerHTML
.replace(/<td([^>]*)>/, '<th$1>')
.replace(/<\/td>/, '</th>')
);
console.log(el.outerHTML);
/*
<table>
<tbody>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
<tr>
<td>Ron</td>
<td>28</td>
</tr>
</tbody>
</table>
*/

Related

how to get tbody header titles using with javascript jquery?

I am creating html table and getting table values using JavaScript.
How to get table header titles?
Date CAIFI
Jun-14 2.217
Jun-15 2.154
Jun-16 1.556
This is my table.
I wrote the code
var value = $("#whatifanalysisTable tbody tr:nth-child(1)").find("td:eq(1)").text();
alert(value);
getting value 2.217
but how to get table name with "Date" and "CAIFI"?
I added your version and changed version in snipped which is also mentioned by Rory in comments. Hope its helpfull.
tbody to thead
td to th
var value = $("#whatifanalysisTable tbody tr:nth-child(1)").find("td:eq(1)").text();
console.log(value);
var headerValue = $("#whatifanalysisTable thead tr:nth-child(1)").find("th:eq(1)").text();
console.log(headerValue);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="tg" id="whatifanalysisTable">
<thead>
<tr>
<th class="tg-0lax">DATE</th>
<th class="tg-0lax">CAIFI</th>
</tr>
</thead>
<tbody>
<tr>
<td class="tg-0lax">Jun - 14</td>
<td class="tg-0lax">2.217</td>
</tr>
</tbody>
</table>

Applying CSS class to all rows but not the table heading

I am trying to apply a css style to change color of clicked rows of an HTML table. On the click event, I am adding the class (selected-row). Now, my table has a sorting functionality when clicking on the heading of each column. The heading gets colored which is not what I want. I want only rows but not the heading. So, I changed my style to (not first child). Now, the heading AND first row don't get color changed. I need only the heading to NOT change color and all other rows to change color when I add selected-row class.
.selected-row:not(:first-child) {
background-color: brown;
color: #FFF;
}
$("#example tr").click(function () {
$(this).addClass('selected-row').siblings().removeClass('selected-row');
});
If you mark up your table with a <thead> to contain the header row, and <tbody> to contain the data rows, you can specifically target only rows in the table body - like this in CSS:
tbody > tr { }
And like this in jQuery:
$('#example tbody > tr')...
Table mark-up:
<table>
<caption>This table contains...</caption>
<thead>
<tr>
<th>Heading</th>
<th>Heading</th>
</tr>
</thead>
<tfoot>
<tr>
<td>Total</td>
<td>$50</td>
</tr>
</tfoot>
<tbody>
<tr>
<td>Item 1</td>
<td>$20</td>
</tr>
<tr>
<td>Item 2</td>
<td>$30</td>
</tr>
</tbody>
</table>
One way to potentially do it would be to wrap your table header in <thead></thead> and body in <tbody></tbody> and then apply whatever selector as
$("#example tbody tr").click(function () {...});
You can target "td" tags:
$("#example tr td").click(function () {
$(this).parent().addClass('selectedrow').siblings().removeClass('selected-row');
If you are using "th" tags in your table:
<table style="width:100%">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
</table>
If you don't want to modify your header using the th or tbody tags, you could do something like this.
$("table tr:gt(0)").click(function(){
$(this).siblings().removeClass('selected-row');
$(this).addClass('selected-row');
})
You can see this working in this jsfiddle
Use th for the header row element.

how to get first table row "<td></td>" text which are visible using jquery

Here I have a table
<table id="table">
<thead>
<tr>
<th>Name</th>
<th>Course</th>
</tr>
</thead>
<tbody>
<tr style="display:none">
<td>jones</td>
<td>.net</td>
</tr>
<tr style="display:none">
<td>James</td>
<td>SAP</td>
</tr>
<tr>
<td>Charles</td>
<td>Java</td>
</tr>
</tbody>
</table>
I want to get text of first row first td text which are visible using jquery, by
above table, I want result as "Charles".
How can get it. I have tried like
$("#table").closest('tbody').children('tr:first').find('td:first').text()
but not getting result.how can I?
Try to use :visible selector to get the visible rows,
$("#table tbody tr:visible:first td:first").text()
To get the visible one use the according :visible selector that jquery ships:
$('#table > tbody > tr:visible:first > td:first').text();
This is Worked for Me.
$('#table> tbody > tr:visible').first().find('td').first().text();

Selecting rows in a table and replacing them with the new data

I have a table with headers:
<table id="my-table">
<thead>
<th>header1</th>
<th>header2</th>
<th>header3</th>
</thead>
<tbody>
<tr>
<td>data1</td>
<td>data2</td>
<td>data3</td>
</tr>
</tbody>
</table>
How do I select only rows and replace them with the new data using jQuery? Only rows and not headers.
You could use the context of the jquery selector as well...
$("tr", "#my-table tbody").each(function (i, item) {
$("td", this).each(function () {
// do something with the td.
});
});
try this
$('#my-table tbody tr td').each(function(){//to select all rows in the table with id my-table
$(this).text('test');
});
It seems obvious, I would try this
$("#my-table tbody tr")
Or this
$("#my-table tr:has(td)")
$('tr').not('thead tr').addClass('selected').

index of tr with tds only --- relative to click

How do I get the index of the <tr> in the table but only if it has <td>s and not <th>s
If I use a click event below it will alert the index of the with td and th but I only want <tr> with <td>s
thanks
$('td').click(function(){
var s = $(this).parents('table tr:has(td)').index();////// returns
alert(s);
});
<table>
<tr>
<th><th><th><th><th><th><th><th><th><th>
</tr>
<tr>
<td><td><td><td><td><td><td><td><td><td>
</tr>
<tr>
<td><td><td><td><td><td><td><td><td><td>
</tr>
<tr>
<td><td><td><td><td><td><td><td><td><td>
</tr>
<tr>
<td><td><td><td><td><td><td><td><td><td>
</tr>
</table>
Try this...
$('td').click(function(){
if ( ! $(this).closest('table').find('th').length ) {
var s = $(this).closest('tr').index();
alert(parseInt(s) + 1);
}
});​
JS FIDDLE LINK
Your given code is working properly. see this jsfiddle.

Categories

Resources