W3C home > Mailing lists > Public > public-webapps@w3.org > October to December 2011

innerHTML in DocumentFragment

From: Yehuda Katz <wycats@gmail.com>
Date: Thu, 3 Nov 2011 16:03:53 -0700
Message-ID: <CAMFeDTUYAGd+0em97f=3GRGRSrfJ-w=_=HAA_grxTtO_myBYZg@mail.gmail.com>
To: public-webapps WG <public-webapps@w3.org>
It would be useful if there was a way to take a String of HTML and parse it
into a document fragment. This should work even if the HTML string contains
elements that are invalid in the "in body" insertion mode.

Something like this code should work:

  var frag = document.createDocumentFragment();
  frag.innerHTML = "<tr><td>hello</td></tr>"
  someTable.appendChild(frag)

At present, this can sometimes be achieved if the context of the HTML
string is known in advance. However, this is not always the case. For
instance, jQuery supplies an API that looks like this:

  $("html string").appendTo("#table")

At the time that jQuery is creating the document fragment for the HTML
string, it does not yet know what its context will be. This approach is
used in order to enable convenient setup code. Here is a very contrived
example to illustrate the point:

  var frag = $("html string")

  // replace the HTML content of a descendent <span> with the contents of
its data-title attribute
  frag.find("span[data-title]").html(function() { return
this.attr("data-title"); })

  html.appendTo("#table")

In general, this makes it easier to build abstractions that work with
Strings of HTML, without always needing to make sure consumers of the
abstraction know and pass in the existing context.

This would probably require a new, laxer insertion mode, which would behave
similarly to the body insertion mode, but with different semantics in the "*A
start tag whose tag name is one of: "caption", "col", "colgroup", "frame",
"head", "tbody", "td", "tfoot", "th", "thead", "tr""* case. One way to
handle those cases would be to immediately enter an appropriate insertion
mode if an unexpected tag was found. For instance, if a start tr tag was
encountered "at the root", the parser could go into "in table" or "in table
body" insertion mode instead of treating it like a parse error and ignoring
the token.

-- Yehuda


-- 
Yehuda Katz
(ph) 718.877.1325
Received on Thursday, 3 November 2011 23:04:25 GMT

This archive was generated by hypermail 2.3.1 : Tuesday, 26 March 2013 18:49:48 GMT