Skip to content

Instantly share code, notes, and snippets.

@tsulli
Created January 18, 2018 14:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tsulli/23bbd392bc58f07e6c3edd1a3435cb25 to your computer and use it in GitHub Desktop.
Save tsulli/23bbd392bc58f07e6c3edd1a3435cb25 to your computer and use it in GitHub Desktop.
Script that creates THEAD out of THs in first row if one is not present (or creates a blank one) for jQuery DataTables
/*
x20170622 - sullivtm - 22 June 2017
Uses SpryMedia's Datatables jQuery Plug-in.
TO USE: Put this on a page with a plain table and add class="RWDtable" to the table tag. If a thead is not present,
one will be created out of the first row of THs or a blank one will be added so SpryMedia's DataTable plug-in works.
Do not use colspan for table cells.
Supports multiple tables on one page.
*/
$(document).ready(function(){
$('table.RWDtable').each(function() {
if ($(this).find('tbody').length === 0){
$(this).wrap('<tbody/>');
}
if ($(this).find('thead').length === 0){
var firstrow = $(this).find('tbody tr:first');
if (firstrow.find('th').length > 0) { // if first row has th tags
firstrow.wrap('<thead/>').parent().prependTo($(this)); // wrap with thead, get tbody, append to table
} else { //if not, make an empty thead row
var thead = firstrow.clone();
thead.children().empty();
thead.children('td').replaceWith(function() {return '<th></th>';});
thead.wrap('<thead/>').parent().prependTo($(this));
}
}
});
$('.RWDtable').DataTable( { responsive: true, paging: false, searching: false, info: false, ordering: false } );
$('.RWDtable').css('width','100%');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment