Created
April 1, 2014 06:29
-
-
Save hayes/9908764 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var document = require('dom-lite').document | |
, htmlparser = require('htmlparser2') | |
var el_proto = Object.getPrototypeOf(document.createElement('p')) | |
, node_proto = Object.getPrototypeOf(el_proto) | |
Object.defineProperty(el_proto, 'innerHTML', { | |
get: get_html | |
, set: set_html | |
}) | |
function get_html() { | |
return node_proto.toString.call(this) | |
} | |
function set_html(html) { | |
var parser = new htmlparser.Parser(new htmlparser.DomHandler(parsed)) | |
, self = this | |
parser.write(html) | |
parser.end() | |
function parsed(err, nodes) { | |
if(err) { | |
throw err | |
} | |
add_children(self, nodes) | |
} | |
} | |
function add_children(root, nodes) { | |
var attrs | |
, el | |
for(var i = 0, l = nodes.length; i < l; ++i) { | |
if(nodes[i].type === 'text') { | |
el = document.createTextNode(nodes[i].data) | |
} else if(nodes[i].type === 'tag') { | |
el = document.createElement(nodes[i].name) //should be createElementNS | |
attrs = Object.keys(nodes[i].attribs) | |
for(var j = 0, l = attrs.length; j < l; ++j) { | |
el.setAttribute(attrs[j], nodes[i].attribs[attrs[j]]) | |
} | |
add_children(el, nodes[i].children) | |
} else { | |
//should add suport for comment nodes | |
continue | |
} | |
root.appendChild(el) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment