b-fuze / deno-dom

Browser DOM & HTML parser in Deno
https://jsr.io/@b-fuze/deno-dom
MIT License
408 stars 48 forks source link

More elegant way to parse DocumentFragments #108

Open caramboleyo opened 2 years ago

caramboleyo commented 2 years ago

Hey,

currently i am parsing document fragments like this and i am wondering if there is a more elegant way:

import { DOMParser } from "https://deno.land/x/deno_dom/deno-dom-wasm.ts";
const proxy = new DOMParser().parseFromString("", "text/html");

function parseFragmentFromString(source) {
    proxy.body.innerHTML = source;
    const fragment = proxy.createDocumentFragment();
    fragment.replaceChildren(...proxy.body.childNodes);
    return fragment;
}
const fragment = parseFragmentFromString("<main-container><h1>Heading</h1><p>Paragraph</p></main-container>");
console.log(">>>fra", fragment);

Also i see that there is a proper function to create an empty document here, but its not accessible: https://github.com/b-fuze/deno-dom/blob/master/src/dom/document.ts#L22

I know you want to stick to the standards, but i think they are kind of incomplete when it comes to parse only parts of html not whole documents. I would expect the DOMParser to have two methods parseDocumentFromString and parseFragmentFromString. I am actually creating an empty document, parsing tons of html snippets as fragments into each other and add them finally to the document.

Any thoughts on this?

b-fuze commented 2 years ago

Can I ask why you need fragments?

caramboleyo commented 2 years ago

Its practically a template, that is not attached to the dom, but can be queried with querySelector and easily modified. Its how i handle the fragments of views. And it can contain not just one root element but a real template with text nodes and so. Its safer to handle. Most dom interpretations always force a whole document on you, i think thats weird. When i have a template of a list, iths not a dcoument its just an ul with lis in it - a fragment.

b-fuze commented 2 years ago

There's a small problem with that... A document fragment is expected to have an .ownerDocument, as stated in the DOM spec

image

So if I were to give you an API for creating stand-alone document fragments I'd basically create an empty document and essentially do the same thing that you're doing 🤔

Also, you can create DocumentFragments with new DocumentFragment() btw. They're not an illegal constructor