UNPKG

1.84 kBJavaScriptView Raw
1'use strict';
2
3var cheerio = require('cheerio'),
4 tableStyleAttrMap = {
5 table: {
6 float: 'align',
7 'background-color': 'bgcolor',
8 width: 'width',
9 height: 'height'
10 },
11 tr: {
12 'background-color': 'bgcolor',
13 'vertical-align': 'valign',
14 'text-align': 'align'
15 },
16 'td,th': {
17 'background-color': 'bgcolor',
18 width: 'width',
19 height: 'height',
20 'vertical-align': 'valign',
21 'text-align': 'align',
22 'white-space': 'nowrap'
23 },
24 'tbody,thead,tfoot': {
25 'vertical-align': 'valign',
26 'text-align': 'align'
27 }
28 },
29 applyStylesAsProps = function ($el, styleToAttrMap) {
30 var style,
31 styleVal;
32
33 for (style in styleToAttrMap) {
34 styleVal = $el.css(style);
35
36 if (styleVal !== undefined) {
37 $el.attr(styleToAttrMap[style], styleVal);
38 $el.css(style, '');
39 }
40 }
41 },
42 batchApplyStylesAsProps = function ($el, sel, $) {
43 $el.find(sel).each(function (i, childEl) {
44 applyStylesAsProps($(childEl), tableStyleAttrMap[sel]);
45 });
46 };
47
48cheerio.prototype.resetAttr = function (attribute) {
49 if (!this.attr(attribute)) {
50 this.attr(attribute, 0);
51 }
52 return this;
53};
54
55module.exports = function (el, $) {
56 var selector,
57 $el = $(el);
58
59 $el = $el.resetAttr('border')
60 .resetAttr('cellpadding')
61 .resetAttr('cellspacing');
62
63 for (selector in tableStyleAttrMap) {
64 if (selector === 'table') {
65 applyStylesAsProps($el, tableStyleAttrMap.table);
66 } else {
67 batchApplyStylesAsProps($el, selector, $);
68 }
69 }
70};