Permalink
Browse files

Smarter HTML parsing

  • Loading branch information...
1 parent 623cdd1 commit 2273346b759739bde5e331da32417ab51b976439 @SteveSanderson SteveSanderson committed May 12, 2011
Showing with 20 additions and 4 deletions.
  1. +20 −4 src/utils.domManipulation.js
@@ -1,9 +1,25 @@
(function () {
function simpleHtmlParse(html) {
- // This code is to be replaced in a moment with something more intelligent
- var dummy = document.createElement("div");
- dummy.innerHTML = html;
- return ko.utils.makeArray(dummy.childNodes);
+ // Based on jQuery's "clean" function, but only accounting for table-related elements.
+ // If you have referenced jQuery, this won't be used anyway - KO will use jQuery's "clean" function directly
+
+ // Trim whitespace, otherwise indexOf won't work as expected
+ var tags = ko.utils.stringTrim(html).toLowerCase(), div = document.createElement("div");
+
+ // Finds the first match from the left column, and returns the corresponding "wrap" data from the right column
+ var wrap = tags.match(/^<(thead|tbody|tfoot)/) && [1, "<table>", "</table>"] ||
+ !tags.indexOf("<tr") && [2, "<table><tbody>", "</tbody></table>"] ||
+ (!tags.indexOf("<td") || !tags.indexOf("<th")) && [3, "<table><tbody><tr>", "</tr></tbody></table>"] ||
+ /* anything else */ [0, "", ""];
+
+ // Go to html and back, then peel off extra wrappers
+ div.innerHTML = wrap[1] + html + wrap[2];
+
+ // Move to the right depth
+ while (wrap[0]--)
+ div = div.lastChild;
+
+ return ko.utils.makeArray(div.childNodes);
}
ko.utils.parseHtmlFragment = function(html) {

0 comments on commit 2273346

Please sign in to comment.