removeAttributesBySelector.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. 'use strict';
  2. const { querySelectorAll } = require('../lib/xast.js');
  3. exports.name = 'removeAttributesBySelector';
  4. exports.type = 'visitor';
  5. exports.active = false;
  6. exports.description =
  7. 'removes attributes of elements that match a css selector';
  8. /**
  9. * Removes attributes of elements that match a css selector.
  10. *
  11. * @example
  12. * <caption>A selector removing a single attribute</caption>
  13. * plugins: [
  14. * {
  15. * name: "removeAttributesBySelector",
  16. * params: {
  17. * selector: "[fill='#00ff00']"
  18. * attributes: "fill"
  19. * }
  20. * }
  21. * ]
  22. *
  23. * <rect x="0" y="0" width="100" height="100" fill="#00ff00" stroke="#00ff00"/>
  24. * ↓
  25. * <rect x="0" y="0" width="100" height="100" stroke="#00ff00"/>
  26. *
  27. * <caption>A selector removing multiple attributes</caption>
  28. * plugins: [
  29. * {
  30. * name: "removeAttributesBySelector",
  31. * params: {
  32. * selector: "[fill='#00ff00']",
  33. * attributes: [
  34. * "fill",
  35. * "stroke"
  36. * ]
  37. * }
  38. * }
  39. * ]
  40. *
  41. * <rect x="0" y="0" width="100" height="100" fill="#00ff00" stroke="#00ff00"/>
  42. * ↓
  43. * <rect x="0" y="0" width="100" height="100"/>
  44. *
  45. * <caption>Multiple selectors removing attributes</caption>
  46. * plugins: [
  47. * {
  48. * name: "removeAttributesBySelector",
  49. * params: {
  50. * selectors: [
  51. * {
  52. * selector: "[fill='#00ff00']",
  53. * attributes: "fill"
  54. * },
  55. * {
  56. * selector: "#remove",
  57. * attributes: [
  58. * "stroke",
  59. * "id"
  60. * ]
  61. * }
  62. * ]
  63. * }
  64. * }
  65. * ]
  66. *
  67. * <rect x="0" y="0" width="100" height="100" fill="#00ff00" stroke="#00ff00"/>
  68. * ↓
  69. * <rect x="0" y="0" width="100" height="100"/>
  70. *
  71. * @link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors|MDN CSS Selectors
  72. *
  73. * @author Bradley Mease
  74. *
  75. * @type {import('../lib/types').Plugin<any>}
  76. */
  77. exports.fn = (root, params) => {
  78. const selectors = Array.isArray(params.selectors)
  79. ? params.selectors
  80. : [params];
  81. for (const { selector, attributes } of selectors) {
  82. const nodes = querySelectorAll(root, selector);
  83. for (const node of nodes) {
  84. if (node.type === 'element') {
  85. if (Array.isArray(attributes)) {
  86. for (const name of attributes) {
  87. delete node.attributes[name];
  88. }
  89. } else {
  90. delete node.attributes[attributes];
  91. }
  92. }
  93. }
  94. }
  95. return {};
  96. };