davestewart
7/3/2016 - 12:13 PM

jQuery plugin to stylize table columns based on the table <col> tag styling

jQuery plugin to stylize table columns based on the table 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;

};