You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

setTableAttrs.js 1.9KB

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