Re: innerHTML in DocumentFragment

On Fri, 04 Nov 2011 00:48:29 +0100, Anne van Kesteren <annevk@opera.com>  
wrote:

> On Thu, 03 Nov 2011 16:44:49 -0700, Tim Down <timdown@gmail.com> wrote:
>> Have you looked at the createContextualFragment() method of Range?
>>
>> http://html5.org/specs/dom-parsing.html#dom-range-createcontextualfragment
>
> That requires a context. Yehuda wants a way of parsing where you do not  
> know the context in advance.
>

This is something I've always wanted, so I always wrote my piece of code  
to make the task easier. But I do suggest a different solution:

Instead of

# var f = document.createDocumentFragment()
# f.innerHTML = '...';

which is quite verbose, I would suggest a simpler API, like

# var document_fragment_node = parseFragment(markup_fragment, Node  
contextNode, boolean safe);
# var element_node           = parseNode    (markup_fragment, Node  
contextNode, boolean safe);
# var document_node          = parseDocument(markup_fragment, boolean  
safe);

* markup_fragment is the html string, or xml depending on the type of  
document of the ownerDocument of contextNode.
* contextNode is an Element for parsing context and to know the  
ownerDocument, or if context is not important, the Document which will be  
the ownerDocument of the resulting fragment
* stripScripts is a boolean that tells the parser to strip unsafe content  
like scripts, event listeners and embeds/objects which would be handled by  
a 3rd party plugin according to user agent policy.

- parseFragment parses a markup fragment which may not have a single root  
element, hence having siblings, with context.
- parseFragment parses a markup fragment which must have a single root  
element, so the DocumentFragment can be spared. This is usually the most  
wanted use case.
- parseDocument similar to DOMParser but for html.

At least for me, an API with these features are everything that I've ever  
needed.

Thanks.

Received on Friday, 4 November 2011 12:55:13 UTC