stringify.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import { isTag, isCDATA, isText, hasChildren, isComment, } from "domhandler";
  2. import renderHTML from "dom-serializer";
  3. import { ElementType } from "domelementtype";
  4. /**
  5. * @category Stringify
  6. * @deprecated Use the `dom-serializer` module directly.
  7. * @param node Node to get the outer HTML of.
  8. * @param options Options for serialization.
  9. * @returns `node`'s outer HTML.
  10. */
  11. export function getOuterHTML(node, options) {
  12. return renderHTML(node, options);
  13. }
  14. /**
  15. * @category Stringify
  16. * @deprecated Use the `dom-serializer` module directly.
  17. * @param node Node to get the inner HTML of.
  18. * @param options Options for serialization.
  19. * @returns `node`'s inner HTML.
  20. */
  21. export function getInnerHTML(node, options) {
  22. return hasChildren(node)
  23. ? node.children.map((node) => getOuterHTML(node, options)).join("")
  24. : "";
  25. }
  26. /**
  27. * Get a node's inner text. Same as `textContent`, but inserts newlines for `<br>` tags.
  28. *
  29. * @category Stringify
  30. * @deprecated Use `textContent` instead.
  31. * @param node Node to get the inner text of.
  32. * @returns `node`'s inner text.
  33. */
  34. export function getText(node) {
  35. if (Array.isArray(node))
  36. return node.map(getText).join("");
  37. if (isTag(node))
  38. return node.name === "br" ? "\n" : getText(node.children);
  39. if (isCDATA(node))
  40. return getText(node.children);
  41. if (isText(node))
  42. return node.data;
  43. return "";
  44. }
  45. /**
  46. * Get a node's text content.
  47. *
  48. * @category Stringify
  49. * @param node Node to get the text content of.
  50. * @returns `node`'s text content.
  51. * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent}
  52. */
  53. export function textContent(node) {
  54. if (Array.isArray(node))
  55. return node.map(textContent).join("");
  56. if (hasChildren(node) && !isComment(node)) {
  57. return textContent(node.children);
  58. }
  59. if (isText(node))
  60. return node.data;
  61. return "";
  62. }
  63. /**
  64. * Get a node's inner text.
  65. *
  66. * @category Stringify
  67. * @param node Node to get the inner text of.
  68. * @returns `node`'s inner text.
  69. * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Node/innerText}
  70. */
  71. export function innerText(node) {
  72. if (Array.isArray(node))
  73. return node.map(innerText).join("");
  74. if (hasChildren(node) && (node.type === ElementType.Tag || isCDATA(node))) {
  75. return innerText(node.children);
  76. }
  77. if (isText(node))
  78. return node.data;
  79. return "";
  80. }
  81. //# sourceMappingURL=stringify.js.map