diff --git a/__tests__/index.test.tsx b/__tests__/index.test.tsx index 96bd1a9e..e76b19b0 100644 --- a/__tests__/index.test.tsx +++ b/__tests__/index.test.tsx @@ -144,6 +144,38 @@ describe('replace option', () => { expect(checks).toEqual([true, true, true]); }); + it('provides text and comment nodes that are instances of the exported classes', () => { + const checks: boolean[] = []; + + parse('Hello world', { + replace(domNode) { + if ( + domNode instanceof HTMLReactParser.Text && + domNode.data === 'Hello ' + ) { + checks.push(true); + } + + if ( + domNode instanceof HTMLReactParser.Element && + domNode.name === 'strong' + ) { + const [text] = domNode.children; + checks.push(text instanceof HTMLReactParser.Text); + } + + if ( + domNode instanceof HTMLReactParser.Comment && + domNode.data === 'note' + ) { + checks.push(true); + } + }, + }); + + expect(checks).toEqual([true, true, true]); + }); + it('replaces the element if a valid React element is returned', () => { expect( parse(html.complex, { diff --git a/src/dom-to-react.ts b/src/dom-to-react.ts index b8803813..4594e40c 100644 --- a/src/dom-to-react.ts +++ b/src/dom-to-react.ts @@ -1,6 +1,10 @@ /* eslint-disable @typescript-eslint/no-unsafe-enum-comparison */ -import { Element as DomHandlerElement } from 'domhandler'; +import { + Comment as DomHandlerComment, + Element as DomHandlerElement, + Text as DomHandlerText, +} from 'domhandler'; import type { DOMNode, Element, Text } from 'html-dom-parser'; import type { JSX } from 'react'; import { cloneElement, createElement, isValidElement } from 'react'; @@ -155,13 +159,19 @@ export default function domToReact( function normalizeDOMNodes(nodes: DOMNode[]): void { for (const node of nodes) { - if ( - node.type === 'tag' || - node.type === 'script' || - node.type === 'style' - ) { - Object.setPrototypeOf(node, DomHandlerElement.prototype); - normalizeDOMNodes(node.children as DOMNode[]); + switch (node.type) { + case 'tag': + case 'script': + case 'style': + Object.setPrototypeOf(node, DomHandlerElement.prototype); + normalizeDOMNodes(node.children as DOMNode[]); + break; + case 'text': + Object.setPrototypeOf(node, DomHandlerText.prototype); + break; + case 'comment': + Object.setPrototypeOf(node, DomHandlerComment.prototype); + break; } } }