Skip to content

Instantly share code, notes, and snippets.

@davestewart
Created July 3, 2016 12:13
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 davestewart/07b117b8b93a23ebfab01f83c1368b86 to your computer and use it in GitHub Desktop.
Save davestewart/07b117b8b93a23ebfab01f83c1368b86 to your computer and use it in GitHub Desktop.
jQuery plugin to stylize table columns based on the table <col> tag styling
var $ = jQuery;
/**
* Upgrade Columns jQuery plugin
*
* Upgrades colgroup formatting to CSS styles
*/
$.fn.upgradeColumns = function()
{
// variables
var pluginName = 'upgrade-columns';
var attrName = 'data-' + pluginName;
var styles = '';
// upgrade tables
$(this)
.each(function(i, e)
{
// table
var $e = $(e);
if($e.attr('data-upgrade-columns'))
{
return;
}
// columns
var $cols = $e.find('col');
if($cols.length == 0)
{
$cols = $e.find('tr:first-of-type > *');
}
// build styles
var attrValue = Date.now() + '-' + i;
var selector = 'table[' +attrName+ '="' + attrValue + '"]';
$cols.each(function(i, e)
{
var style = $.trim($(e).attr('style'));
if(style)
{
styles += selector + ' tr > *:nth-child(' + (i+1) + '){' +style+ '}\n';
}
});
// flag table as processed
$e.attr(attrName, attrValue);
});
// assign
if(styles)
{
$('<style type="text/css" data-plugin="' +pluginName+ '">').text(styles).appendTo('head');
}
// return
return this;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment