Precise DOM morphing
morphing typescript dom

Improve document handling

+43 -3
+4 -3
src/morphlex.ts
··· 33 33 * 34 34 * @param from The source document to morph from. 35 35 * @param to The target document or string to morph to. 36 + * @param options Optional configuration for the morphing behavior. 36 37 * @example 37 38 * ```ts 38 - * morphDocument(document, newDocument) 39 + * morphDocument(document, "<html>...</html>", { preserveModified: true }) 39 40 * ``` 40 41 */ 41 - export function morphDocument(from: Document, to: Document | string): void { 42 + export function morphDocument(from: Document, to: Document | string, options?: Options): void { 42 43 if (typeof to === "string") to = parseDocument(to) 43 - morph(from.documentElement, to.documentElement) 44 + morph(from.documentElement, to.documentElement, options) 44 45 } 45 46 46 47 /**
+39
test/new/document.ts
··· 1 + import { test, expect } from "vitest" 2 + import { morphDocument } from "../../src/morphlex" 3 + 4 + test("morphing an entire document", () => { 5 + const parser = new DOMParser() 6 + const originalDocument = parser.parseFromString( 7 + ` 8 + <html> 9 + <head> 10 + <title>Original Title</title> 11 + <meta name="description" content="original"> 12 + </head> 13 + <body> 14 + <div id="content">Original Content</div> 15 + </body> 16 + </html> 17 + `, 18 + "text/html", 19 + ) 20 + 21 + morphDocument( 22 + originalDocument, 23 + ` 24 + <html> 25 + <head> 26 + <title>New Title</title> 27 + <meta name="description" content="new"> 28 + </head> 29 + <body> 30 + <div id="content">New Content</div> 31 + </body> 32 + </html> 33 + `, 34 + ) 35 + 36 + expect(document.title).toBe("New Title") 37 + expect(document.querySelector('meta[name="description"]')?.getAttribute("content")).toBe("new") 38 + expect(document.querySelector("#content")?.textContent).toBe("New Content") 39 + })